简体   繁体   English

while 语句中的无限循环

[英]infinite loop in a while statement

    import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        System.out.println("\nThe sum of the numbers is: " + getSumOfInput());
    }

    public static int getSumOfInput () {
        int counter = 0;
        int sumOfNums = 0;

        Scanner userInput = new Scanner(System.in);

        while(counter <= 10) {
            System.out.print("Enter the number " + counter + ": ");

            boolean checkValidity = userInput.hasNextInt();

            if(checkValidity) {
                int userNum = userInput.nextInt();
                userInput.nextLine();

                System.out.println("Number " + userNum + " added to the total sum.");
                sumOfNums += userNum;
                counter++;

            } else {
                System.out.println("Invalid input. Please, enter a number.");
            }

        }

        userInput.close();

        return sumOfNums;
    }

}

Hello everybody!大家好!

I just started java and I learned about control flow and now I moved on to user input, so I don't know much.我刚开始 java 并了解了控制流,现在我转向用户输入,所以我不太了解。 The problem is this code.问题是这段代码。 Works just fine if you enter valid input as I tested, nothing to get worried about.如果您输入我测试的有效输入,则工作正常,无需担心。 The problem is that I want to check for wrong input from user, for example when they enter a string like "asdew".问题是我想检查用户的错误输入,例如当他们输入像“asdew”这样的字符串时。 I want to display the error from else statement and to move on back to asking the user for another input, but after such an input the program will enter in an infinite loop displaying "Enter the number X: Invalid input. Please, enter a number.".我想显示 else 语句中的错误并继续询问用户另一个输入,但是在这样的输入之后,程序将进入一个无限循环,显示“输入数字 X:无效输入。请输入一个数字."。

Can you tell me what's wrong?你能告诉我有什么问题吗? Please, mind the fact that I have few notions when it comes to what java can offer, so your range of solutions it's a little bit limited.请注意,当谈到 java 可以提供什么时,我几乎没有什么概念,因此您的解决方案范围有点有限。

The issue is, that once you enter intput, which can not be interpreted as an int , userInput.hasNextInt() will return false (as expected).问题是,一旦您输入不能解释为int的 intput , userInput.hasNextInt()将返回 false (如预期的那样)。 But this call will not clear the input, so for every loop iteration the condition doesn't change.但是此调用不会清除输入,因此对于每次循环迭代,条件都不会改变。 So you get an infinite loop.所以你得到一个无限循环。

From Scanner#hasNextInt() :Scanner#hasNextInt()

Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method.如果此扫描器输入中的下一个标记可以使用 nextInt() 方法解释为默认基数中的 int 值,则返回 true。 The scanner does not advance past any input.扫描仪不会超过任何输入。

The fix is to clear the input if you came across invalid input.解决方法是在遇到无效输入时清除输入。 For example:例如:

    } else {
        System.out.println("Invalid input. Please, enter a number.");
        userInput.nextLine();
    }

Another approach you could take, which requires less input reads from the scanner, is to always take the next line regardless and then handle the incorrect input while parsing.您可以采用的另一种方法(需要从扫描仪读取较少的输入)是始终采用下一行,然后在解析时处理不正确的输入。

public static int getSumOfInput() {
    int counter = 0;
    int sumOfNums = 0;

    Scanner userInput = new Scanner(System.in);

    while (counter <= 10) {
        System.out.print("Enter the number " + counter + ": ");

        String input = userInput.nextLine();
        try {
            int convertedInput = Integer.parseInt(input);
            System.out.println("Number " + convertedInput + " added to the total sum.");
            sumOfNums += convertedInput;
            counter++;
        } catch (NumberFormatException e) {
            System.out.println("Invalid input. Please, enter a number.");
        }
    }

    return sumOfNums;
}

Call userInput.nextLine();调用userInput.nextLine(); just after while : while之后:

...
while(counter <= 10) {
  System.out.print("Enter the number " + counter + ": ");
  userInput.nextLine();
...

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

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