我正在写一个简单的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新手
发布于 2011-11-04 10:16:03
nextInt()不会丢弃不匹配的输出;程序将尝试一遍又一遍地读取它,每次都会失败。在调用nextInt()之前,使用hasNextInt()方法确定是否有int可供读取。
确保当您在InputStream中发现整数以外的内容时,可以使用nextLine()清除它,因为hasNextInt()也不会丢弃输入,它只是测试输入流中的下一个标记。
发布于 2014-06-24 02:19:48
尝试使用
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/的共同主题
https://stackoverflow.com/questions/8004185
复制相似问题