昨天我读了关于for循环的Java中的逗号运算符。这符合我的预期。我想到了这种结构,但它没有按预期工作。
';' expected
} while((userInput < 1 || userInput > 3), wrongInput = true);
';' expected
} while((userInput < 1 || userInput > 3), wrongInput = true);
我的想法是,在一次迭代后,如果userInput
不在1和3之间,则应将布尔wrongInput
设置为true
,以便在下一次迭代期间出现错误消息显示。表明userInput
无效。
private int askUserToSelectDifficulty() {
int userInput;
Boolean wrongInput = false;
do{
if(wrongInput) println("\n\t Wrong input: possible selection 1, 2 or 3");
userInput = readInt();
} while((userInput < 1 || userInput > 3), wrongInput = true);
return userInput;
}
我想这可能因为它在for循环的条件部分之内,这是无效的语法。因为您不能在条件部分中使用逗号运算符?
我在for-loops中看到逗号运算符的示例:Giving multiple conditions in for loop in Java Java - comma operator outside for loop declaration
答案 0 :(得分:3)
最好稍微展开一下。
userInput = readInt();
while (userInput < 1 || userInput > 3) {
System.out.println("\n\tWrong input: possible selection 1, 2 or 3");
userInput = readInt();
}
这避免了需要标志。
答案 1 :(得分:1)
Java中没有逗号运算符(无论如何都不是C / C ++意义上的)。在某些情况下,您可以使用逗号一次声明和初始化多个内容,但这并不会推广到其他上下文,例如示例中的上下文。
表达循环的一种方法是:
while (true) {
userInput = readInt();
if (userInput >= 1 && userInput <= 3) {
break;
}
println("\n\t Wrong input: possible selection 1, 2 or 3");
};