当前位置: 首页 > 面试题库 >

Java InputMismatchException

池照
2023-03-14
问题内容

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

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循环来消除first input.nextInt()

do {
    try {
        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);

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



 类似资料:

相关阅读

相关文章

相关问答