简体   繁体   English

Java:将hasNextInt与do-while循环配合使用,它会在偶数时间忽略整数输入

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

I am trying to learn Java programming by myself and came across the course CS106A provided by Stanford. 我试图自己学习Java编程,并且遇到了斯坦福大学提供的CS106A课程。 It's a great free online course. 这是一个很棒的免费在线课程。 I watched several of the lecture videos and I enjoyed them so far. 我看了几个演讲视频 ,到目前为止我都很喜欢。 I am now trying to do the assignments and I have this problem I can't solve by myself. 我现在正在尝试做作业,但有我自己无法解决的问题。

It is the number 5 of this assignment . 这是该作业的数字5。 Basically, it requires the learner to create a console program to get some integers input by the user and in response, showing the biggest and smallest number. 基本上,它要求学习者创建一个控制台程序来获取用户输入的一些整数并作为响应,以显示最大和最小的数字。

The following code is what I have done and the problem is when I try to input integers, it will skip the even number of inputs. 下面的代码是我所做的,问题是当我尝试输入整数时,它将跳过输入的偶数。 For instance if I enter 3,12,6,15,9 to the console, it will only get 3,6,9 , ignoring 12,15. 例如,如果我在控制台中输入3,12,6,15,9,则只会得到3,6,9,而忽略12,15。

What did I do wrong? 我做错了什么? Any help would be appreciated. 任何帮助,将不胜感激。

import java.util.*;

public class Ass2_5MaxMinNumbers {
    public static void main (String args[]) {
        Scanner scanner;

        System.out.println ("This programme finds the largest and smallest numbers.");
        System.out.println ("After finished entering, enter \"End\" (without double quotes) to show the results.");

        List<Integer> list = new ArrayList<Integer>();
        int max = 0, min = 0;

        do {
            scanner = new Scanner(System.in);

            if(scanner.hasNextInt()){
                int x = scanner.nextInt();
                list.add(x);
                System.out.println("user input: " + x);
            } else if(!scanner.hasNext("End")){
                System.out.println("Please enter an integer!");
            }
        } while (!scanner.hasNext("End"));

        max = list.get(0);
        min = list.get(0);
        for(int x = 1; x < list.size(); x++){
            if(list.get(x) > max){
                max = list.get(x);
            } else if(list.get(x) < min){
                min = list.get(x);
            }
        }

        System.out.println ("Smallest number: " + min);
        System.out.println ("Biggest number: " + max);
    }
}

Scanner.nextInt method only reads the next token from the input passed from user. Scanner.nextInt方法仅从用户传递的输入中读取下一个标记。 So, it ignores the linefeed that is at the end of each input. 因此,它会忽略每个输入末尾的linefeed And that linefeed goes as input to the next call to Scanner.nextInt , and hence your input is ignored. 该换行符将作为下一个对Scanner.nextInt调用的输入,因此您的输入将被忽略。

You can use a blank Scanner.nextLine after each call to Scanner.nextInt to consume the linefeed. 您可以在每次调用Scanner.nextLine之后使用空白的Scanner.nextInt来消耗换行符。

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 . 或者,您也可以仅使用scanner.nextLine()读取integers ,然后使用Integer.parseInt将输入转换为integer

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. 实际上,由于您在if中使用了scanner.hasNextInt ,因此您实际上不需要在Integer.parseInt周围进行try-catch ,因此可以将其删除。


UPDATE : - 更新:-

I would replace your do-while with a while and just remove the if-else check from inside. 我将用一段while替换您的do-while ,然后从内部删除if-else检查。

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. 您发布的代码中的错误是您正在使用循环的每次迭代来创建新的Scanner对象。 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. 顺便说一句-最大值和最小值可以在while循环内计算,而无需先将这些值存储在List中。

Thank you for calling this free on-line class to my attention. 感谢您致电我注意这个免费的在线课程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM