问题
Im trying to add an input validation to this menu. When the user enters eg: 'a' or any input that is not a integer and with the given range, it must execute the catch block and loop again to prompt the user to enter again but instead it keeps looping infinitely after taking the input once. So it goes from executing the menu and just skipping over the input part and executes the catch block.
Edit: it goes into infinite loop if i input anything that is not an integer.
Scanner sc = new Scanner(System.in);
int x = 1;
do{
try
{
System.out.println("Select option ");
System.out.println("1) Circle ");
System.out.println("2) Rectangle ");
System.out.println("3) Triangle ");
System.out.println("4) Exit ");
x = sc.nextInt();
}
catch(Exception e)
{
System.out.print("Invalid data");
}
}while(x<1 || x>4);
回答1:
The issue is that you are not flushing the buffer when the Scanner gets a character/string instead of an int. In addition, your loop will terminate if a character/string is read in on the first iteration since your loop condition will return false with x set initially to 1. You can fix this by setting it to -1 instead. Moreover, instead of using a try catch block, you can use the hasNextInt() method to check if the user is typing in an int or not.
Scanner sc = new Scanner(System.in);
int x = -1;
do {
System.out.println("Select option ");
System.out.println("1) Circle ");
System.out.println("2) Rectangle ");
System.out.println("3) Triangle ");
System.out.println("4) Exit ");
if (sc.hasNextInt())
{
x = sc.nextInt();
}
else
{
System.out.println("Invalid input. Please try again.");
// Flush the buffer
sc.nextLine();
}
} while (x < 1 || x > 4);
sc.close();
回答2:
Put
sc.nextLine();
next
x = sc.nextInt();
来源:https://stackoverflow.com/questions/60014004/do-while-goes-into-an-infinite-loop