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();
}
-
Number 2 has to be greater than number 1
-
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
rinstead of a number the program just exits.
Use
Scanner.hasNextInt():Here’s a snippet to illustrate:
You don’t have to
parseIntor worry aboutNumberFormatException. Note that since thehasNextXXXmethods don’t advance past any input, you may have to callnext()if you want to skip past the “garbage”, as shown above.Related questions