7

このコードがあり、レター例外をキャッチしたいのですが、これらのエラーが引き続き発生します。

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

5 に答える 5

3

ドキュメントから

Scanner.nextInt 入力の次のトークンを int としてスキャンします。次のトークンが整数正規表現と一致しないか、範囲外の場合

したがって、入力として整数を入力していないようです。

あなたが使用することができます

     while (students <= 0) {

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

            students = input1.nextInt();

         }

         catch (InputMismatchException e) {
             input1.nextLine();
         }
     } 
于 2013-05-29T14:14:30.977 に答える