【发布时间】: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