Java: using hasNextInt with do-while loop, it ignores integer inputs at even times

爷,独闯天下 提交于 2019-12-06 09:25:25

Scanner.nextInt method only reads the next token from the input passed from user. So, it ignores the linefeed that is at the end of each input. And that linefeed goes as input to the next call to Scanner.nextInt, and hence your input is ignored.

You can use a blank Scanner.nextLine after each call to Scanner.nextInt to consume the linefeed.

if(scanner.hasNextInt()){
    int x = scanner.nextInt();
    scanner.nextLine();  // Add a blank nextLine
    list.add(x);
    System.out.println("user input: " + x);
}

Or you can also use scanner.nextLine() only for reading integers, and convert the input to integer using Integer.parseInt.

if(scanner.hasNextInt()) {
    int x = 0;

    try {
         x = Integer.parseInt(scanner.nextLine());
    } catch (NumberFormatException e) {
         e.printStackTrace();
    }

    list.add(x);
    System.out.println("user input: " + x);
}

Actually, since you are using scanner.hasNextInt in your if, you don't really need that try-catch around your Integer.parseInt, so you can remove that.


UPDATE : -

I would replace your do-while with a while and just remove the if-else check from inside.

while (scanner.hasNextLine()) {
    String input = scanner.nextLine();

    if (input.equals("End")) {
        break;
    } else {
        try {
            int num = Integer.parseInt(input);
            list.add(num);

        } catch (NumberFormatException e) {
            System.out.println("Please Enter an Integer");
        }
    }
}

The mistake in the code you posted is that you are creating a new Scanner object with ever iteration of your loop. Initialize the scanner before the loop and your code works:

    scanner = new Scanner(System.in);
    do {
      if(scanner.hasNextInt()){
            int x = scanner.nextInt();
            list.add(x);
            System.out.println("user input: " + x);
        }
        //and so on...

BTW - the max and min values can be calculated inside the while loop without first storing the values in a List.

Thank you for calling this free on-line class to my attention.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!