Java InputMismatchException

后端 未结 3 1860
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-06 03:01

I have this code and I want to catch the letter exception but it keeps having these errors:

Exception in thread \"main\" java.util.InputMismatchException
            


        
相关标签:
3条回答
  • 2020-12-06 03:57

    Reading data from Scanner and assigning it to Int type. Since you are supplying String this will throw exception. To handle this situation you must write your snippet inside Try- Catch block only.

    0 讨论(0)
  • 2020-12-06 03:58

    You can use a do-while loop instead to eliminate the 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);
    

    Therefore all InputMismatchException can be handled in one place.

    0 讨论(0)
  • 2020-12-06 03:59

    from the doc

    Scanner.nextInt Scans the next token of the input as an int. if the next token does not match the Integer regular expression, or is out of range

    So it seems you are not entering any integer as input.

    you can use

         while (students <= 0) {
    
             try {
                System.out.print("Enter the number of students: ");
    
                students = input1.nextInt();
    
             }
    
             catch (InputMismatchException e) {
                 input1.nextLine();
             }
         } 
    
    0 讨论(0)
提交回复
热议问题