【问题标题】:Loop Prints Else Statement Only循环仅打印 Else 语句
【发布时间】:2025-09-11 22:15:02
【问题描述】:

我正在从事某种数学培训计划。我正在尝试实现一个 for 循环,以便用户选择的每个问题类型都会生成三个问题。如果用户输入正确的变量类型,这将非常有效。但是,如果用户输入了错误的变量/变量类型,则会发生这种情况,它会以一种奇怪的方式循环。这很难解释,但如果你拿代码并尝试给它错误的输入,你很快就会看到。我不确定这可能是如何引起的,所以我想我会在这里发帖。我已经注释掉了,因此只有一种操作类型(添加)可用,仅用于调试目的。如果您键入的内容与程序预期的内容不同,您将看到。我对循环很陌生,并且在多种想法上都尽了最大努力,但我做不到。谢谢!

    // 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!");
}

}

【问题讨论】:

  • 请访问How to Ask页面和Edit您的问题。我们不需要你的整个程序,只需要足够的代码来重新创建/理解问题。
  • 当您在调试器中单步执行代码时,您会看到什么?哪一行代码没有达到你的预期?
  • 如果我输入 'z' 而不是 a、s、m、d 或 r,例如,程序会打印 else 语句 3 次。

标签: java loops if-statement for-loop math


【解决方案1】:

如果我输入 'z' 而不是 a、s、m、d 或 r,例如,程序会打印 else 语句 3 次。

假设3次是因为Config.NUMBER_OF_QUESTIONS是3,那是因为你在循环外执行了String userLetter = stdin.nextLine();,所以userLetter的值永远不会改变。

如果您修复了代码的缩进,那么for 循环的范围就会变得清晰,您会发现您需要在循环内移动以下行:

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

原答案

hasNextDouble() 不消耗任何内容,因此当您提出问题时,如果用户回复 I don't know 而不是输入数字,则文本会保留。

当你再问下一个问题时,上一个问题的(坏)答案仍在缓冲区中,系统也会失败下一次hasNextDouble()调用,依此类推,依此类推,...

这是人们使用Scanner 的主要缺陷之一。他们忘记了错误处理。

在这种情况下,每行给出一个答案,因此,每当您阅读答案时,您都应该在之后致电nextLine(),以丢弃答案后的任何额外文本,或者如果输入错误则丢弃整行给定的。

【讨论】:

  • 我不确定我是否完全理解。因此,如果我键入非双精度信息,无论如何都会存储并留在那里?我相信它的输出方式是有道理的。例如,如果用户输入“z”而不是“a”会怎样。程序打印 else 语句 3 次。我想我需要在它再次开始循环之前清除它,但我仍然很困惑。
  • 哦!这是有道理的,我不敢相信我没有听懂。谢谢。