Java InputMismatchException

后端 未结 3 1869
爱一瞬间的悲伤
爱一瞬间的悲伤 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: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.

提交回复
热议问题