===== CS302 TOOL BOX =====
T > COIN TOSS SIMULATOR
G > GRADE ESTIMATOR
C > COLOR CHALLENGE
Q > QUIT
Type code letter for your choices: h
Invalid selection. Please try agian:
t
Invalid selection. Please try agian:
T
^这是我在运行程序时给出的错误猜测。循环用于验证用户输入,因此它完全失败。关于我做错了什么的任何想法?谢谢你的时间!
}
System.out.println("===== CS302 TOOL BOX =====");
System.out.println("T > COIN TOSS SIMULATOR");
System.out.println("G > GRADE ESTIMATOR");
System.out.println("C > COLOR CHALLENGE");
System.out.println("Q > QUIT");
System.out.print("Type code letter for your choices: ");
boolean code_letter;
String code_choice = scanner.next();
do {
if (code_choice.toUpperCase().equals("Q")
|| (code_choice.toUpperCase()).equals("C")
|| (code_choice.toUpperCase()).equals("G")
|| (code_choice.toUpperCase()).equals("T")) {
code_letter = true;
}
else {
System.out.println("Invalid selection. Please try agian: ");
code_letter = false;
scanner.next();
}
} while (!(code_letter));
{
System.out.println("you did it?");
}
}
}
答案 0 :(得分:1)
初始化code_choice
循环中的do-while
变量,否则变量将不会在条件测试之前的循环的每次迭代中重新初始化。
String code_choice = scanner.next();
像这样
//declared it outside to take care of the scope
String code_choice = null;
do {
//initialize it every time before you perform the conditional test.
//This increases the readability!
code_choice = scanner.next();
if (code_choice.toUpperCase().equals("Q")
|| (code_choice.toUpperCase()).equals("C")
|| (code_choice.toUpperCase()).equals("G")
|| (code_choice.toUpperCase()).equals("T")) {
code_letter = true;
}
else {
System.out.println("Invalid selection. Please try agian: ");
code_letter = false;
}
} while (!(code_letter));
希望这有帮助!
答案 1 :(得分:0)
试试..
把你的
scanner.next()
在if之前的,删除
周围的花括号System.out.println("you did it?");
最后你的......改变它......
while(code_letter != true);
答案 2 :(得分:0)
我假设扫描仪(小写S)是扫描仪对象?请在下次包含所有相关代码,否则调试问题非常困难。
你遇到的主要问题是在else条件下的行。 scanner.next()不做任何事情。你需要这样做:
else {
System.out.println("Invalid selection. Please try agian: ");
code_letter = false;
code_choice = scanner.next(); // This needs to be modified
}
这应该让它发挥作用。