Java 输入不匹配异常

新手上路,请多包涵

我有这段代码,我想捕获字母异常,但它一直有这些错误:

 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)
    at exercise_one.Exercise.main(Exercise.java:17)

这是我的代码:

  System.out.print("Enter the number of students: ");

 students = input.nextInt();

 while (students <= 0) {

     try {

        System.out.print("Enter the number of students: ");

        students = input.nextInt();

     }

     catch (InputMismatchException e) {

        System.out.print("Enter the number of students");

     }
 }

原文由 John Stef 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 685
2 个回答

您可以改用 do-while 循环来消除第一个 input.nextInt()

 int students = 0;
do {
    try {
        // Get input
        System.out.print("Enter the number of students: ");
        students = input.nextInt();
    } catch (InputMismatchException e) {
        System.out.print("Invalid number of students. ");
    }
    input.nextLine(); // clears the buffer
} while (students <= 0);

// Do something with guaranteed valid value

因此所有 InputMismatchException 都可以在一个地方处理。

原文由 Siyu Song 发布,翻译遵循 CC BY-SA 4.0 许可协议

文档

Scanner.nextInt 将输入的下一个标记扫描为 int。如果下一个标记与 Integer 正则表达式不匹配,或者超出范围

因此,您似乎没有输入任何整数作为输入。

您可以使用

     while (students <= 0) {

         try {
            System.out.print("Enter the number of students: ");

            students = input1.nextInt();

         }

         catch (InputMismatchException e) {
             input1.nextLine();
         }
     }

原文由 stinepike 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题