How do I ensure that Scanner hasNextInt() asks for new input?

前端 未结 2 1301
隐瞒了意图╮
隐瞒了意图╮ 2020-12-19 20:33

New programmer here. This is probably a really basic question, but it\'s stumping me nevertheless.

What I\'m trying to do is write a method that supplies only one in

2条回答
  •  粉色の甜心
    2020-12-19 21:29

    //while (test == false) {                         // Line #1
    while (!test) { /* Better notation */             // Line #2
        System.out.println("Integers only please");   // Line #3
        test = input.hasNextInt();                    // Line #4
    }                                                 // Line #5
    

    The problem is that in line #4 above, input.hasNextInt() only tests if an integer is inputted, and does not ask for a new integer. If the user inputs something other than an integer, hasNextInt() returns false and you cannot ask for nextInt(), because then an InputMismatchException is thrown, since the Scanner is still expecting an integer.

    You must use next() instead of nextInt():

    while (!input.hasNextInt()) {
        input.next();
        // That will 'consume' the result, but doesn't use it.
    }
    int result = input.nextInt();
    input.close();
    return result;
    

提交回复
热议问题