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

前端 未结 2 1224
隐瞒了意图╮
隐瞒了意图╮ 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:08

    You were close: this works fine for me:

    Scanner input = new Scanner(System.in); //construct scanner
    while(!input.hasNextInt()) {
        input.next(); // next input is not an int, so consume it and move on
    }
    int finalInput = input.nextInt();
    input.close(); //closing scanner
    System.out.println("finalInput: " + finalInput);
    

    By calling input.next() in your while loop, you consume the non-integer content and try again, and again, until the next input is an int.

    0 讨论(0)
  • 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;
    
    0 讨论(0)
提交回复
热议问题