简体   繁体   English

为什么我的 do-while 循环在使用 Java 扫描仪输入无效输入后变成无限循环?

[英]Why does my do-while loop become an infinite loop after entering an invalid input with the Java Scanner?

When you type in anything besides a number it will just print my "Invalid response:" for forever.当您输入除数字以外的任何内容时,它将永远打印我的“无效响应:”。 But when you type in a number it will go on to the next one (working correctly).但是当你输入一个数字时,它会 go 到下一个(正常工作)。

I don't understand why it's continuously printing my error message when it fails the check.我不明白为什么它在检查失败时不断打印我的错误消息。 Instead, I want it to ask the user for input again.相反,我希望它再次要求用户输入。

If you know of a better more efficient way please help me out.如果您知道更好更有效的方法,请帮助我。

public class Test {

    public static void main(String[] args) {
        //Scanner getting input
        Scanner nin = new Scanner(System.in); //input for numbers
        Scanner sin = new Scanner(System.in); //input for yes or no

        //initialize variables
        String input = "";
        boolean valid = false;
        boolean playAgain = false;

        //Primary Do While
        do {
            System.out.println("This program will ask for three numbers and see which one is the largest\n");
            System.out.println("\n\n");

            //define the range
            int num1 = 0;
            int num2 = 0;
            int num3 = 0;
            int largestNum = 0;

            //numeric input validation who while loop for the first number
            do {
                System.out.println("Please enter the frist number: ");

                //if block to check if input is valid
                if (nin.hasNextInt()) {
                    num1 = nin.nextInt();
                    valid = true;
                } else {
                    System.out.println("Invalid response: Please enter a whole number.\n\n");
                    valid = false;
                    nin.hasNext();
                }


            } while (!valid); //if false run the loop
            valid = false; //this resets the validity for the next number

            //numeric input validation who while loop for the second number
            do {
                System.out.println("Please enter the second number: ");

                //if block to check if input is valid
                if (nin.hasNextInt()) {
                    num2 = nin.nextInt();
                    valid = true;
                } else {
                    System.out.println("Invalid response: Please enter a whole number.\n\n");
                    valid = false;
                    nin.hasNext();
                }

            } while (!valid); //if false run the loop
            valid = false; //this resets the validity for the next number

            //numeric input validation who while loop for the third number
            do {
                System.out.println("Please enter the second number: ");

                //if block to check if input is valid
                if (nin.hasNextInt()) {
                    num3 = nin.nextInt();
                    valid = true;
                } else {
                    System.out.println("Invalid response: Please enter a whole number.\n\n");
                    valid = false;
                    nin.hasNext();
                }

            } while (!valid); //if false run the loop


            //passing numbers to method and saving results to variable 
            largestNum = largestNum(num1, num2, num3);

            //printing the results
            System.out.println(largestNum);


        } while (!playAgain);


    }

    private static int largestNum(int num1, int num2, int num3) {
        if (num1 > num2 && num1 > 3) {
            return num1;
        } else if (num2 > num1 && num2 > num3) {
            return num2;
        } else {
            return num3;
        }

    }

}

First, you do not need 2 Scanner objects because you are reading from the same place.首先,您不需要 2 个Scanner对象,因为您是从同一个地方读取的。

Remember - whatever you need to read, one Scanner per file is enough!请记住 - 无论您需要阅读什么,每个文件一个Scanner就足够了!

But the real problem is that you do not clear the invalid user input.但真正的问题是您没有清除无效的用户输入。 The method hasNext only checks to see if there is more input ready to be processed, but does nothing with it. hasNext方法只检查是否有更多输入准备好处理,但不做任何事情。

If you find that there is still input but it is not an integer ( hasNext returns true but hasNextInt returns false ) you should call next method, to get the remaining input regardless of type (ignoring the returned value).如果您发现仍有输入但不是 integer ( hasNext返回truehasNextInt返回false )您应该调用next方法,以获取剩余的输入,无论类型如何(忽略返回值)。

Also, since you need 3 loops that are identical, it would be better to just put one loop in to a separate private method that would return the value, and then call that method 3 times.此外,由于您需要 3 个相同的循环,因此最好将一个循环放入一个单独的返回值的私有方法中,然后调用该方法 3 次。

privat int getNumberFromUser() {
    do {
        //your loop code here
    } while (!valid);

    return num;
}

//in main:
num1 = getNumberFromUser();
num2 = getNumberFromUser();
num3 = getNumberFromUser();

Your code never actually reads the bad input, as it reads the valid input using nextInt .您的代码从未真正读取错误输入,因为它使用nextInt读取有效输入。 ( hasNext just tells whether or not there is input to be read.) hasNext只是告诉是否有要读取的输入。)

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

相关问题 如果您提供无效的输入,为什么这个“ do / while / for循环”永远不会结束? - Why does this `do-while/for loop` never end if you give an invalid input? Do-While 循环在输入用户输入时显示很多错误(Java -OSGi Equinox in Eclipse EE - Do-While loop is showing a lot of error while entering user input (Java -OSGi Equinox in Eclipse EE 为什么此Java渲染使用嵌套的do-while循环? - Why does this Java rendering use a nested do-while loop? 为什么do-while循环在这个Java程序中没有按预期运行? - Why does the do-while loop not run as expected in this Java program? 为什么我的do-while循环在Java中中断太早? - Why is my do-while loop breaking too early in java? 扫描仪输入+ do-while循环表现得非常奇怪 - Scanner input + do-while loop behaving very strangely 在 do-while 循环中输入不适用于扫描仪 class - Input not working with Scanner class in the do-while loop Java输入缓冲区和do-while循环行为(为什么它会检查第一个字符3次?) - Java input buffer and do-while loop behavior (why does it check first character 3 times?) 为什么此do-while循环不起作用? - Why does this do-while loop not function? 由于某种原因,我的do-while循环第一次执行时,扫描程序两次要求输入 - For some reason, the first time my do-while loop executes, the scanner asks for input twice
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM