我正在研究各种各样的数学培训计划。我正在尝试实现一个 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!");
}
}
例如,如果我输入"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()
,以丢弃答案后的任何额外文本,或者如果输入错误,则丢弃整行。