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

前端 未结 2 1304
隐瞒了意图╮
隐瞒了意图╮ 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.

提交回复
热议问题