-2

While trying to read a number using below code InputMismatchError is generated:

Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {

    long number = sc.nextLong(); // Error here

    if (number % 2 == 0 && number != 0) {
        System.out.println("even");
    } else if (number % 2 != 0 && number != 0) {
        System.out.println("odd");
    } else if (number == 0) {
        System.out.println("");
    }
}

I don't understand where a mistake. Eclipse compiled program without errors.

Following is the input from console used

1234.5

Sanyam Goel
  • 2,138
  • 22
  • 40
Timur Shubin
  • 35
  • 1
  • 9
  • That'll happen if you enter something that's not a `long`. Did you, by any chance, enter non-numeric characters there? Also, just because it compiles doesn't mean it'll run. – user May 29 '20 at 14:06
  • 2
    What are you entering on the command line? Also, you could change to `while (sc.hasNextLong()) {` – 001 May 29 '20 at 14:06
  • It might be safer to do what JohnnyMopp said and check if there's another long, and if not, consume the next word and print an error message telling the user to re-enter the long – user May 29 '20 at 14:07
  • I enter integers, Long is set, as there may be large numbers. hasNextLong() didn't work – Timur Shubin May 29 '20 at 14:12
  • Hyperskill tests throws error, but Eclipse work without errors. – Timur Shubin May 29 '20 at 14:35
  • I assume that's one of the coding competition sites. My guess is it is expecting you to ignore any bad input but still continue. – 001 May 29 '20 at 14:39

2 Answers2

0

If the input might have some non-integers with the values, you should check if the next value is a long. If not, ignore it:

while (sc.hasNext()) {
    // Check if next is a long
    if (sc.hasNextLong()) {
        long number = sc.nextLong();

        if (number == 0) {
            System.out.println("");
        }
        else if (number % 2 == 0) {
            System.out.println("even");
        }
        else {
            System.out.println("odd");
        }
    }
    else {
        // Not a long, consume rest of line.
        // You might need to change this to sc.next() depending on requirements
        sc.nextLine();
    }
}
001
  • 13,291
  • 5
  • 35
  • 66
0

You could do this way

Scanner scan = new Scanner(System.in);
long val = scan.nextLong();
System.out.printf(String.valueOf(val));

while you are expecting long you should pass non-decimal numeric value from command line.

Anshul Sharma
  • 1,018
  • 3
  • 17
  • 39