我正在进行各种数学训练计划。我试图实现一个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!");
}
}
答案 0 :(得分:1)
如果我输入&#39; z&#39;例如,程序打印else语句3次,而不是a,s,m,d或r。
假设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()
,在答案后丢弃任何额外的文字,或者如果不好则丢弃整行输入已经给出。