我需要以下代码的帮助:
int seatNum = 0;
Scanner seatNumber = new Scanner(System.in);
do
{
try
{
System.out.println("Please choose a seat number");
seatNum = seatNumber.nextInt();
}
catch(InputMismatchException e)
{
System.out.println("The index you have entered is invalid");
System.out.println("Please enter an index number between 0 and 7");
}
} while (seatNum <= 0 || seatNum >= 7);
基本上,我只想让seatNum在0到7之间(如果不要求用户再次输入)。当我输入一个介于0到7之间的整数时,一切都可以正常工作,但是如果我输入一个String,程序将进入无限循环。当用户输入String时,如何停止进入无限循环的程序?
最佳答案
尝试这个
String seatNum = null;
Scanner scanner = new Scanner(System.in);
while(true){
System.out.println(" Enter a number between 0 and 7");
seatNum = scanner.nextLine().toString();
if(seatNum.matches("[0-7]")) break; // makes sure user enter a number also between the range
else System.out.println("Enter between 0 and 7");
不错吧?我没有运行它,告诉它是否是您想要的