【问题标题】:infinite loop in a while statementwhile 语句中的无限循环
【发布时间】:2021-05-12 19:16:26
【问题描述】:
    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;
    }

}

大家好!

我刚开始学习 java 并且学习了控制流,现在我开始学习用户输入,所以我不太了解。问题是这段代码。如果您输入我测试的有效输入,则工作正常,无需担心。问题是我想检查用户的错误输入,例如当他们输入像“asdew”这样的字符串时。我想显示 else 语句中的错误并继续询问用户另一个输入,但是在这样的输入之后,程序将进入一个无限循环,显示“输入数字 X:无效输入。请输入一个数字。”。

你能告诉我有什么问题吗?请注意,我对 java 可以提供的功能几乎没有概念,因此您的解决方案范围有点有限。

【问题讨论】:

  • 您是否尝试过将 userInput.nextLine() 也放入 else 语句?
  • 是的......现在我意识到,你是对的。现在它起作用了。我只在 if 语句的一部分中使用了它,但它本身就挂了。祝你有美好的一天,非常感谢!
  • 太好了,你也是 :)

标签: java input while-loop


【解决方案1】:

while 之后致电userInput.nextLine();

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

【讨论】:

  • 感谢您的帮助!原来是这个问题,现在好了。
【解决方案2】:

问题是,一旦输入不能解释为int 的输入,userInput.hasNextInt() 将返回 false(如预期的那样)。但是这个调用不会清除输入,所以对于每次循环迭代,条件都不会改变。所以你得到一个无限循环。

来自Scanner#hasNextInt()

如果此扫描器输入中的下一个标记可以使用 nextInt() 方法解释为默认基数中的 int 值,则返回 true。扫描仪不会超过任何输入。

解决方法是在遇到无效输入时清除输入。例如:

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

您可以采取的另一种方法(需要从扫描仪读取的输入更少)是始终采用下一行,然后在解析时处理不正确的输入。

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;
}

【讨论】:

  • 感谢您提供的信息。现在我对它的工作原理有了清晰的认识。效果很好。
  • 如果您有时间,请提供一些信息。在我的情况下,解析方法应该返回一个 int 无论如何?我的意思是我输入“203x43”之类的内容。它将排除字符元素并仅选择整数?与 double 和所有其他数字基本类型一样吗?
  • 不,它只会正确解析有效的整数(在字符串表示中)。因此,如果字符串中包含任何无效字符,它将失败。查看Integer.parseInt(String s)
  • 这是一个很好的了解方法。谢谢你的信息!
  • 但请注意,对于无效输入,NumberFormatException 将被抛出。请参阅我的答案中的示例。
猜你喜欢
  • 2013-03-26
  • 2013-05-17
  • 1970-01-01
  • 2013-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-29
  • 1970-01-01
相关资源
最近更新 更多