int memberChoice;
boolean accountLoop = true;
while (accountLoop) {
try {
System.out.println("Would you like to be a... \n1.Basic Member or \n2.Premium member");
memberChoice = input.nextInt();
if (memberChoice == 1 || memberChoice == 2) {
accountLoop = false;
}
if (memberChoice < 1 || memberChoice > 2) {
System.out.println("Please choose either 1 or 2");
}
System.out.println();
} catch (InputMismatchException e) {
System.out.println("Invalid input");
}
}
每当我输入一个字符串时,它应该说无效输入会回到循环的开头并指示我再次输入一个数字。相反,它给了我一个无限循环。我觉得它的东西真的很小但我已经在这里呆了5个小时而且无法理解它。有什么建议吗?
答案 0 :(得分:0)
对我来说,你的代码工作得很好。你的ide可能有问题。无论如何,将行if (memberChoice < 1 || memberChoice > 2)
更改为if (memberChoice < 1 && memberChoice > 2)
答案 1 :(得分:0)
将input = new Scanner(System.in);
添加到catch块,因为我假设您正在使用扫描仪读取标准输入...
当出现问题时,这将重新初始化扫描仪。
当放入&#34;字符串&#34;扫描仪将尝试将其读作nextInt(),除非您再次初始化它,否则它将继续失败...
答案 2 :(得分:0)
使用try / catch块来路由代码逻辑是不好的做法。例外情况应保留用于特殊情况,并且从不用于通过应用程序控制信息流。
相反,您可以使用(假定的)扫描程序对象的其他方法在尝试为其分配类型之前验证传入的元素。
public static void main(String[] args) {
int memberChoice=0;
System.out.println("Would you like to be a... \n1.Basic Member or \n2.Premium member");
//Use Try with Resources to ensure the Scanner is closed when we're done (requires Java 1.7+)
try (Scanner input = new Scanner(System.in)){
//hasNextLine tells us the user has entered a value.
while (input.hasNextLine() && (memberChoice != 1 && memberChoice != 2)) {
//Is that value actually an int?
if (input.hasNextInt()) {
//YES - Read as int and check for the value we're expecting
int inValue = input.nextInt();
if (inValue == 1 || inValue == 2) {
memberChoice = inValue;
} else {
System.out.println("Invalid choice. Try again");
System.out.println("Would you like to be a... \n1.Basic Member or \n2.Premium member");
System.out.println();
}
} else {
//NO - Read the line, provide feedback and prompt the user for a correction.
String line = input.nextLine();
System.out.println("You have to enter an integer value. '"+ line + "' is not valid.");
System.out.println("Would you like to be a... \n1.Basic Member or \n2.Premium member");
System.out.println();
}
}
}
}
答案 3 :(得分:0)
这就是我解决问题的方法:
int memberChoice = -1;
boolean accountLoop = true;
Scanner reader = new Scanner(System.in);
while (accountLoop) {
System.out.println("Would you like to be a... \n1.Basic Member or \n2.Premium member");
try {
memberChoice = reader.nextInt();
if (memberChoice == 1 || memberChoice == 2) {
System.out.println(" Answer was valid ");
accountLoop = false;
}
if (memberChoice < 1 || memberChoice > 2) {
System.out.println("Please choose either 1 or 2");
}
System.out.println();
} catch (InputMismatchException e) {
System.out.println("Invalid input");
reader.next(); // this consumes the invalid token
}
}
reader.close();
使用以下链接解决了这个问题: How to handle infinite loop caused by invalid input using Scanner
这个答案的摘要:
您需要“消费”无效答案。否则,该输入将保留在缓冲区中,这将导致无限循环。