Joo*_*oop 5 java comma while-loop conditional-statements do-while
昨天我读了关于for循环的Java中的逗号运算符.这符合我的预期.我想到了这种结构,但它没有按预期工作.
';' expected
} while((userInput < 1 || userInput > 3), wrongInput = true);
';' expected
} while((userInput < 1 || userInput > 3), wrongInput = true);
Run Code Online (Sandbox Code Playgroud)
我的想法是,在一次迭代后,如果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;
}
Run Code Online (Sandbox Code Playgroud)
我想这也许是因为它在for循环的等效部分内部,这是无效的语法.因为您不能在条件部分中使用逗号运算符?
我看到在for循环中使用逗号运算符的示例:在Java Java 中为for循环提供多个条件- 用于循环声明的逗号运算符
Java 中没有逗号运算符(无论如何不是 C/C++ 意义上的)。在某些上下文中,您可以使用逗号一次声明和初始化多个内容,但这并不能推广到其他上下文,例如您的示例中的上下文。
表达循环的一种方法如下:
while (true) {
userInput = readInt();
if (userInput >= 1 && userInput <= 3) {
break;
}
println("\n\t Wrong input: possible selection 1, 2 or 3");
};
Run Code Online (Sandbox Code Playgroud)