我正在编写一个简单的java控制台游戏。我使用扫描仪从控制台读取输入。我试图验证它我要求一个整数,如果输入一个字母,我不会收到错误。我试过这个:
boolean validResponce = false;
int choice = 0;
while (!validResponce)
{
try
{
choice = stdin.nextInt();
validResponce = true;
}
catch (java.util.InputMismatchException ex)
{
System.out.println("I did not understand what you said. Try again: ");
}
}
但它似乎创建了一个无限循环,只是打印出catch块。我做错了什么。
是的,我是Java的新手
答案 0 :(得分:4)
nextInt()
不会丢弃不匹配的输出;程序将尝试一遍又一遍地阅读,每次都失败。使用hasNextInt()
方法确定在调用int
之前是否可以阅读nextInt()
。
确保当您在InputStream
中找到除整数之外的其他内容时,使用nextLine()
清除它,因为hasNextInt()
也不会丢弃输入,它只会测试下一个标记输入流。
答案 1 :(得分:0)
尝试使用
boolean isInValidResponse = true;
//then
while(isInValidResponse){
//makes more sense and is less confusing
try{
//let user know you are now asking for a number, don't just leave empty console
System.out.println("Please enter a number: ");
String lineEntered = stdin.nextLine(); //as suggested in accepted answer, it will allow you to exit console waiting for more integers from user
//test if user entered a number in that line
int number=Integer.parseInt(lineEntered);
System.out.println("You entered a number: "+number);
isInValidResponse = false;
}
//it tries to read integer from input, the exceptions should be either NumberFormatException, IOException or just Exception
catch (Exception e){
System.out.println("I did not understand what you said. Try again: ");
}
}
由于avoiding negative conditionals
https://blog.jetbrains.com/idea/2014/09/the-inspection-connection-issue-2/