这是我的代码片段:
while (true){
System.out.println("---Welcome to the Shape Machine---");
System.out.println("Available options:");
System.out.println("Circles");
System.out.println("Rectangles");
System.out.println("Triangles");
System.out.println("Exit");
//asks for selection
String option = console.next();
while (!option.equals("Cirlces") && !option.equals("Rectangles") && !option.equals("Triangles") && !option.equals("Exit")){
System.out.println("#ERROR Invalid option. Please try again.");
break;
}
switch (option) {
case "Circles": {
我设置了一个菜单,当用户输入任何不属于选项之一的内容时,它应该打印出错误消息并将用户带回菜单。这按预期工作,但如果我输入正确的输入,错误消息仍然会打印出来,但 switch 语句运行就像没有错误一样,并执行必要的计算。我尝试在 if else 语句中使用 while true 循环,但仍然遇到同样的问题。我还尝试使用 OR 运算符代替 AND 运算符,并使用 != 代替 !().equals 方法。我不知道该怎么做才能修复它。任何帮助将非常感激。
最佳答案
我将在这里进行大胆的猜测,并尝试找出您想要实现的目标。
试试这个:
while (true){
System.out.println("---Welcome to the Shape Machine---");
System.out.println("Available options:");
System.out.println("Circles");
System.out.println("Rectangles");
System.out.println("Triangles");
System.out.println("Exit");
//asks for selection
String option = console.next();
switch (option) {
case "Circles":
//do something
break;
case "Rectangles":
break;
case "Triangles":
break;
case "Exit":
break;
default:
System.err.println("#ERROR Invalid option. Please try again.");
}
//now you can either put a flag or change the code to a DO..While
//depending on if you want to re-execute after each option..
}
如果你想要一个 if 语句,你会想要做(遵循你的版本):
if (!option.equals("Cirlces") && !option.equals("Rectangles") && !option.equals("Triangles") && !option.equals("Exit")){
//print the error, then continue
}
或者,更容易阅读
if( ! ( (option.equals("Circles") || option.equals("Rectangles") || option.equals("Triangles") || option.equals("Exit") ) ){
//print the error, then continue
}
此外,请确保您读取的值正确,尝试将其打印出来并检查。
如果这不起作用,则您未提供的代码中一定有错误,在这种情况下,请发布 MCVE .
关于java - 为什么即使不满足循环内设置的条件,我的循环错误消息也会打印出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40003951/