I have this code. It asks for two integer values. If the first number is not an integer, then it throws an exception and asks the number again. My code works but I'm wondering if there is a better way to do this:
boolean validInput = false;
boolean validInput2 = false;
while (validInput == false) {
try {
Scanner scanner = new Scanner(System.in);
System.out.print("What is the first number? ");
int firstNum = scanner.nextInt();
validInput = true;
} catch (InputMismatchException e) {
System.out.println("It's not an integer.");
}
}
while (validInput2 == false) {
try {
Scanner scanner2 = new Scanner(System.in);
System.out.print("What is the second number? ");
int secondNum = scanner2.nextInt();
scanner2.close();
validInput2 = true;
} catch (InputMismatchException e) {
System.out.println("It's not an integer.");
}
}
I suppose I can do something like this as well. Right?
while (validInput == false) {
Scanner scanner = new Scanner(System.in);
System.out.print("What is the first number? ");
if (scanner.hasNextInt()) {
int firstNum = scanner.nextInt();
validInput = true;
}
}
In the second example when the hasNextInt()
method is called, the scanner waits for a value, that makes sense, and if the condition becomes true, nextInt()
is called, but nextInt()
doesn't wait for input anymore. How does nextInt()
know what the entered value was when the condition executed?