Java InputMismatchException

时间:2013-05-29 14:12:33

标签: java exception-handling while-loop try-catch mismatch

我有这个代码,我想抓住字母异常,但它一直有这些错误:

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

     }
 }    

4 个答案:

答案 0 :(得分:8)

您可以使用do-while循环来消除第一个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都可以在一个地方处理。

答案 1 :(得分:2)

来自doc

  

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

所以你似乎没有输入任何整数作为输入。

你可以使用

     while (students <= 0) {

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

            students = input1.nextInt();

         }

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

答案 2 :(得分:0)

从扫描仪读取数据并将其分配为Int类型。由于您提供的是String,因此将引发异常。要处理这种情况,您必须仅在Try-Catch块中编写代码段。

答案 3 :(得分:0)

如果你想确定所有输入都是整数,你可以试试这个:

while(true) {
            try {
                System.out.print("Kolon sayısını giriniz: ");
                c = scan.nextInt();
                
            } catch (Exception e) {
                System.out.print("Geçersiz giriş.. ");
                scan.nextLine();
                continue;
            }
            break;
        }


// or this...
while(true) {
            System.out.print("Give me a number");
            try {
                input = scan.nextInt();
                break;
            } catch (Exception e) {
                System.out.print("There was mismatch");
                scan.nextLine();
            }
        }