Java 输入不匹配异常

标签 java exception while-loop try-catch

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

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");

     }
 }    

最佳答案

您可以改用 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 都可以在一个地方处理。

关于Java 输入不匹配异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16816250/

相关文章:

java - 所有 RuntimeException/Un-checked 异常的拥护者,你们会如何处理这种情况?

Python while 循环 popleft() - 错误 : Empty deque

c++ - 重新启动后,线程无法在while循环中再次运行

java - 从时间间隔中排除 2 月 29 日

java - 不使用 Spring Security 身份验证?

java - Fragment和Activity之间的通信

c - 在循环不起作用时测试 NULL 值的字符串

java - 为什么我们在 ArrayList<Integer> a1 = new ArrayList<Integer>() 中使用包装类 Integer?

java - 异常处理和初始化

java - 什么时候抛出 "throws Exception"?