I am having problems with understanding why code is not working. My objective is to keep reading the input of the user until the user finally enters "5", to which the code will continue. I appreciate there are likely better ways, and am open to suggestions of more concise ways to go about this (trying to parse a string, perhaps), however my question is more curious as to why my method does not work as opposed to looking for a better method.
The code works perfectly when any integer is input, however if I were to enter a String, the code loops continuously, and the catch block is always started without any input required. I presume it's a feature of the Scanner retaining my input, but I'm not sure.
My code is the following:
import java.util.Scanner;
import java.util.InputMismatchException;
public class App {
public static void main(String[] args) {
int temp = 0;
System.out.println("Enter the number 5: ");
while (temp != 5) {
try {
temp = sc.nextInt();
} catch (InputMismatchException e) {
System.out.println("Try again!");
}
}
System.out.println("Got it!");
sc.close();
}
}