How to use Scanner to accept only valid int as input

John picture John · May 26, 2010 · Viewed 242.8k times · Source

I'm trying to make a small program more robust and I need some help with that.

Scanner kb = new Scanner(System.in);
int num1;
int num2 = 0;

System.out.print("Enter number 1: ");
num1 = kb.nextInt();

while(num2 < num1) {
    System.out.print("Enter number 2: ");
    num2 = kb.nextInt();
}
  1. Number 2 has to be greater than number 1

  2. Also I want the program to automatically check and ignore if the user enters a character instead of a number. Because right now when a user enters for example r instead of a number the program just exits.

Answer

polygenelubricants picture polygenelubricants · May 26, 2010

Use Scanner.hasNextInt():

Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.

Here's a snippet to illustrate:

Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!sc.hasNextInt()) sc.next();
int num1 = sc.nextInt();
int num2;
System.out.print("Enter number 2: ");
do {
    while (!sc.hasNextInt()) sc.next();
    num2 = sc.nextInt();
} while (num2 < num1);
System.out.println(num1 + " " + num2);

You don't have to parseInt or worry about NumberFormatException. Note that since the hasNextXXX methods don't advance past any input, you may have to call next() if you want to skip past the "garbage", as shown above.

Related questions