-3

如果用户不小心输入了错误的输入(字母),我希望程序一次又一次地循环,直到给出正确的输入,但是使用下面的代码我有一些错误。有任何想法吗?

catch (InputMismatchException e) {
      input.nextLine();
      while (!input.hasNextInt()) {
            System.out.print("Enter the number of people in the circle: ");
            numberOfPeople = input.nextInt();
      }
}

错误输出:

Exception in thread "main" java.util.InputMismatchException at 
java.util.Scanner.throwFor(Scanner.java:840) at 
java.util.Scanner.next(Scanner.java:1461) at 
java.util.Scanner.nextInt(Scanner.java:2091) at 
java.util.Scanner.nextInt(Scanner.java:2050)
4

2 回答 2

1

请参阅API

由 Scanner 抛出以指示检索到的令牌与预期类型的​​模式不匹配,或者令牌超出预期类型的​​范围。

这是因为它没有读取正确的类型。

我建议你使用Scanner#hasNextInt()并做这样的事情(注意没有使用 try-catch 块):

if (input.hasNextInt()) {
    numberOfPeople = scanner.nextInt();
}
else {
    input.next();
    continue;
}

我们为什么使用next()? 由于 Java 文档对Scanner的描述:

当扫描器抛出 InputMismatchException 时,扫描器不会传递导致异常的令牌,以便可以通过其他方法检索或跳过它。

于 2013-05-29T15:56:16.963 回答
0

可以做如下的事情

for(int i=1;i<n;i++)
{
try
{
//code for taking the input from user
}
catch(InputMismatchException exception)
{
 //Equivalently keeping the same value of i 
--i;
}

}
于 2013-05-29T15:57:39.123 回答