简体   繁体   English

循环仅打印其他语句

[英]Loop Prints Else Statement Only

I'm working on a math training program of sorts. 我正在制定各种数学培训计划。 I'm trying to implement a for loop so that each question type that the user picks will generate three questions. 我正在尝试实现一个for循环,以便用户选择的每个问题类型将生成三个问题。 This works perfectly if the user enters the correct variable type. 如果用户输入正确的变量类型,这将非常有效。 However, if a user enters the wrong variable/ variable type what happens is that it loops in an odd way. 但是,如果用户输入错误的变量/变量类型,将会发生奇怪的循环。 It's hard to explain but if you take the code and try giving it the wrong input you will soon see. 很难解释,但是如果您采用了代码并尝试输入错误的代码,您很快就会看到。 I'm not sure how this may be caused so I figured I'd post here. 我不确定这可能是怎么造成的,所以我想在这里发布。 I've commented out so that only one operation type (addition) is available, just for debugging purposes. 我已注释掉,因此仅一种操作类型(添加)可用,仅用于调试目的。 If you type something other than what the program expects you will see. 如果您键入的不是程序预期的内容,您将看到。 I'm quite new to loops and have tried my best at multiple ideas but I'm coming up short. 我对循环很陌生,并且在多种想法上都尽力了,但是我很快就提出了。 Thank you! 谢谢!

    // Welcome
    System.out.println("Hello and welcome to the Math Trainer!\n======================================");
    System.out.println("Which math operation would you like to practice?");

    // Print options to select from
    System.out.println("    " + "[A]ddition"); 
    System.out.println("    " +"[S]ubtraction"); 
    System.out.println("    " + "[M]ultiplication");
    System.out.println("    " + "[D]ivision");
    System.out.println("    " + "[R]emainder");

    // Ask for user input on which to choose
    System.out.print("Enter your choice:" + " ");
    String userLetter = stdin.nextLine();

    // Calculate random values from seed and shift them within range
        for(int count = 0; count < Config.NUMBER_OF_QUESTIONS; count++){
        int ran1 = randGen.nextInt(Config.MAX_VALUE - Config.MIN_VALUE + 1);
        int ran2 = randGen.nextInt(Config.MAX_VALUE - Config.MIN_VALUE + 1);
        int ran1Shift = ran1 + Config.MIN_VALUE;
        int ran2Shift = ran2 + Config.MIN_VALUE;

        // Initialize different answers per operation
        double additionAnswer = (double)ran1Shift + ran2Shift;
        double subtractionAnswer = (double)ran1Shift - ran2Shift;
        double multiplicationAnswer = (double)ran1Shift * ran2Shift;
        double divisionAnswer = (double)ran1Shift / ran2Shift;
        double remainderAnswer = (double)ran1Shift % ran2Shift;



    // Prompt user with a question based upon random numbers and operation selection
    // Presentation of addition problems
    if(userLetter.equalsIgnoreCase("a")) {
        System.out.print("What is the solution to the problem:" + " " + ran1Shift + " " + "+" + " " + ran2Shift + " = ");
        if (stdin.hasNextDouble()) {
            double userNum = stdin.nextDouble();
            if (userNum == additionAnswer) {
                System.out.println("That is correct!");
            } else {
                System.out.println("The correct solution is: " + additionAnswer + ".");
            }
        } else {
            System.out.println("All solutions must be entered as decimal numbers.");
            System.out.println("The correct solution is " + additionAnswer + ".");
            }
        }

    else{
    System.out.println("I'm sorry, I only understand choices of: A, S, M, D, or R!");
    }
}

    // Program exit
    System.out.println("======================================");
    System.out.println("Thank you for using the Math Trainer!");
}

} }

If I enter 'z' instead of a, s , m, d, or r, for example, the program prints the else statement 3 times. 例如,如果我输入“ z”而不是a,s,m,d或r,程序将打印else语句3次。

Assuming that 3 times is because Config.NUMBER_OF_QUESTIONS is 3, it is because you execute String userLetter = stdin.nextLine(); 假设3次是因为Config.NUMBER_OF_QUESTIONS为3,那是因为您执行了String userLetter = stdin.nextLine(); outside the loop, so the value of userLetter never changes. 循环之外 ,因此userLetter的值永远不会改变。

If you fix the indentation of your code, so the scope of the for loop becomes clear, you'll see that you need to move the following lines inside the loop: 如果您修复了代码的缩进,那么for循环的范围将变得很清楚,您将看到需要在循环内移动以下几行:

// Ask for user input on which to choose
System.out.print("Enter your choice:" + " ");
String userLetter = stdin.nextLine();

Original Answer 原始答案

hasNextDouble() doesn't consume anything, so when you ask a question, and user responds I don't know instead of typing a number, the text stays. hasNextDouble()不会消耗任何东西,因此当您问一个问题,并且用户响应时, I don't know而不是输入数字,文本仍然存在。

When you then ask the next question, the (bad) answer from previous question is still in the buffer, and the system will fail the next hasNextDouble() call too, and so on, and so on, ... 然后,当您问下一个问题时,上一个问题的(错误)答案仍在缓冲区中,并且下一个hasNextDouble()调用也hasNextDouble()系统失败,依此类推,等等,...

This is one of the main flaws with how people use the Scanner . 这是人们使用Scanner的主要缺陷之一。 They forget error handling. 他们忘记了错误处理。

In this case, answers are give one per line, so any time you read an answer, you should always call nextLine() afterwards, to discard any extra text after the answer, or to discard the entire line if bad input was given. 在这种情况下,每行给出一个答案,因此,每当您阅读答案时,都应始终之后调用nextLine() ,以在答案之后舍弃任何多余的文本,或者在输入错误的情况下舍弃整行。

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

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