How to safely scan for input Integer?

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 handling exceptions, this code will enter an infinite loop when non-integer input is given. Instead of Scannerpausing to collect input in the next iteration, it just keeps throwing InputMismatchExceptionuntil the program is killed.

What is the best way to scan to input an integer (or another type, I suppose), discard invalid input and continue the loop in normal mode?

+5
source share
5 answers

, int, int. , , , .

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

, , int, . .

+4

catch (InputMismatchException exception) 
{ 
    System.out.println("Integers only, please."); 
    scanner.nextLine();
} 
+5

javadoc: InputMismatchException, int, . , .

, , . , catch :

catch (InputMismatchException exception) 
{ 
    System.out.println("Integers only, please."); 
    scanner.next();
}
+3

,

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);



}

}

, . , . , , , .

, , .

do-while, , -, .

0

non-int, , true, .

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 );
0

All Articles