6
Scanner scanner = new Scanner();
int number = 1;

do
{
    try
    {
        option = scanner.nextInt();
    }
    catch (InputMismatchException exception)
    {
        System.out.println("Integers only, please.");
    }
}
while (number != 0);

Despite the exception handling, this code will enter an infinite loop when non-integer input is given. Instead of Scanner pausing to collect input in the next iteration, it simply continues throwing InputMismatchExceptions until the program is killed.

What's the best way to scan for integer (or another type, I suppose) input, discarding invalid input and continuing the loop normally?

Maxpm
  • 24,113
  • 33
  • 111
  • 170

5 Answers5

7

change your code to this

catch (InputMismatchException exception) 
{ 
    System.out.println("Integers only, please."); 
    scanner.nextLine();
} 
samack
  • 815
  • 11
  • 28
  • also add a checker to see if the inputted String holds only numeric chars, if anything else is inputted display an error. – Gonçalo Vieira Sep 16 '11 at 14:49
  • That's why I hate scanner. However +1 – Martijn Courteaux Sep 16 '11 at 15:02
  • It's a 100% good fix, but I am happy there were other answers on here. Without any explanation as to why that fixes it (eg. "nextInt() does not move forward if token translation is unsuccessful"), people learning and using these for reference later on will be able to fix it, but won't understand why it worked. Still, +1 for the answer. – Alex G Mar 09 '14 at 04:30
7

You should check whether or not the input can be parsed as an int before attempting to assign the input's value to an int. You should not be using an exception to determine whether or not the input is correct it is bad practice and should be avoided.

if(scanner.hasNextInt()){
   option = scanner.nextInt();
}else{
   System.out.printLn("your message");
}

This way you can check whether or not the input can be interpreted as an int and if so assign the value and if not display a message. Calling that method does not advance the scanner.

ChadNC
  • 2,528
  • 4
  • 25
  • 39
4

From the javadoc: This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.

Note the second sentence there, it only advances IF it is successful. This means that you will need to change your catch block to something like the following:

catch (InputMismatchException exception) 
{ 
    System.out.println("Integers only, please."); 
    scanner.next();
}
Michael Holman
  • 901
  • 1
  • 10
  • 26
1

If it scans a non-int variable, exception will pop, if not flag will be true and loop will exit.

Scanner scanner = new Scanner();
int number = 1;
boolean flag = false;

do
{
    try
    {
        option = scanner.nextInt();
        flag=true;
    }
    catch (InputMismatchException exception)
    {
        System.out.println("Integers only, please.");
    }
}
while ( flag );
Nick Z.
  • 39
  • 2
0

I think this is better

import java.util.*;

class IntChkTwo{

public static void main(String args[]){

    Scanner ltdNumsScan = new Scanner(System.in);
    int ltdNums = 0;
    int totalTheNums = 0;
    int n = 4;



    System.out.print("Enter Five Numbers: ");
    for(int x=0;x<=n;x++){
        try{
            ltdNums = ltdNumsScan.nextInt();
            totalTheNums = totalTheNums + ltdNums;
        }catch(InputMismatchException exception){
            n+=1;//increases the n value 
                    //maintains the same count of the numbers
                    //without this every error is included in the count
            System.out.println("Please enter a number");
            ltdNumsScan.nextLine();

        }//catch ends
    }//for ends

    int finalTotalNums = totalTheNums;
    System.out.println("The total of all of the five numbers is: "+finalTotalNums);



}

}

I was confused with the code sample, so I had to rewrite it. Hope this helps you even its been years. I know its different, but when I tried adding the numbers using the sample code I got confused along the way.

At first what was bugging me was it counts the error.

I would rather do away with the do-while loop, tried it before and if you miss something it goes on to an infinite loop.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203