有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

while语句中的java无限循环

    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”的字符串时。我想显示error from else语句,并返回到要求用户进行另一个输入,但在这样一个输入之后,程序将进入一个无限循环,显示“输入数字X:无效输入。请输入一个数字”

你能告诉我怎么了吗?请注意,我对java能提供什么没有什么概念,所以您的解决方案范围有点有限


共 (2) 个答案

  1. # 1 楼答案

    while之后调用userInput.nextLine();

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

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

    ^{}

    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. The scanner does not advance past any input.

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

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