views:

124

answers:

2

So I am trying to deal with the possible exception of a user entering a double when my scanner is expecting integral input:

boolean go = true;
do {
        System.out.print("Please enter one grade from 0 - 100. To end input, enter a        
        negative integral value.\n");
    try {
            int myInt = scanner.nextInt();
            .
            .
            .
    }
    catch (InputMismatchException e) {
            System.out.println("Oops!! Please enter only integral numbers");
    }
while (go);

This works for non-numerical input (i.e. a letter), but not if I enter, say 3.14 or another ASCII symbol like -. In that case, the lines below repeat until I kill the program.

Please enter one grade from 0 - 100. To end input, enter a negative integral value.
Oops!! Please enter only integral numbers.

Any ideas? :D

Reply: I am using System.in, and java 6.

+2  A: 

I tried the code you posted above (using a System.in InputStream), and doubles cause an InputMismatchException as expected. What input method are you using, and what version of Java?

Kaleb Brasee
+4  A: 

My guess, that when you say explodes, you mean that you are getting an infinite loop of

Oops!! Please enter only integral numbers

Try doing the following instead:

try {
  int myInt = scanner.nextInt();
  // …
}
catch (InputMismatchException e) {
  System.out.println("Oops!! Please enter only integral numbers");
  System.out.println(scanner.next() + " was not valid input.");
}

Edit: I see that my initial guess was right ;-)

The reason that this is happening is that when nextInt() fails, the internal pointer is not moved on, and so every time that you can nextInt again, it fails on the same token. So, you need to clear the token out first, which is what I am doing by printing out the text that is invalid input. This then causes a new token to be read from the input stream.

Paul Wagland
+1: The token pointer is not moved
bguiz