为什么 ((ans != 'N') || (ans != 'Y')) 总是正确的?
Why is ((ans != 'N') || (ans != 'Y')) always true?
我试图提示用户再次旋转,但我的 "while" 表达式总是返回错误...有人有任何想法吗?
reSpin = false;
if (reSpin == false){
System.out.println("Would you like to spin again? Y/N");
char ans = in.next().charAt(0);
if (ans == 'Y'){
reSpin =true;
}else if (ans == 'N'){
System.out.println("Thank you for playing!");
}else {
while ((ans != 'N') || (ans != 'Y')) {
System.out.println("Invalid answer, please only enter Y/N");
System.out.println("Would you like to spin again? Y/N");
ans = in.next().charAt(0);
}
}
}
您可能想使用:
while ((ans != 'N') && (ans != 'Y')) {
检查 ans
不是 N 和 不是 Y。如果你在那里使用 ||
(or),那么它会检查到看到 ans
要么不是 N,要么不是 Y(对于 ans
的任何值都是如此)。
||
returns 如果 任一侧的表达式中有一个 为真,则为真。
如果ans
是Y
,则ans != 'N'
为真,所以整个表达式(ans != 'N') || (ans != 'Y')
为真。如果 ans
为 N
,则 ans != 'Y'
为真,因此整个表达式为真。
你想要 (ans != 'N') && (ans != 'Y')
,上面写着“ans
is not 'N'
and ans
is also not 'Y'
."
ans
不能同时是 'N' 和 'Y',所以它总是不等于 'N' 或不等于 'Y'.您可能希望将其更改为:
while ((ans != 'N') && (ans != 'Y'))
这确保它既不等于 'N' 也不等于 'Y'。
很简单:根据您的比较,ans
必须同时是 Y
和 N
。
我试图提示用户再次旋转,但我的 "while" 表达式总是返回错误...有人有任何想法吗?
reSpin = false;
if (reSpin == false){
System.out.println("Would you like to spin again? Y/N");
char ans = in.next().charAt(0);
if (ans == 'Y'){
reSpin =true;
}else if (ans == 'N'){
System.out.println("Thank you for playing!");
}else {
while ((ans != 'N') || (ans != 'Y')) {
System.out.println("Invalid answer, please only enter Y/N");
System.out.println("Would you like to spin again? Y/N");
ans = in.next().charAt(0);
}
}
}
您可能想使用:
while ((ans != 'N') && (ans != 'Y')) {
检查 ans
不是 N 和 不是 Y。如果你在那里使用 ||
(or),那么它会检查到看到 ans
要么不是 N,要么不是 Y(对于 ans
的任何值都是如此)。
||
returns 如果 任一侧的表达式中有一个 为真,则为真。
如果ans
是Y
,则ans != 'N'
为真,所以整个表达式(ans != 'N') || (ans != 'Y')
为真。如果 ans
为 N
,则 ans != 'Y'
为真,因此整个表达式为真。
你想要 (ans != 'N') && (ans != 'Y')
,上面写着“ans
is not 'N'
and ans
is also not 'Y'
."
ans
不能同时是 'N' 和 'Y',所以它总是不等于 'N' 或不等于 'Y'.您可能希望将其更改为:
while ((ans != 'N') && (ans != 'Y'))
这确保它既不等于 'N' 也不等于 'Y'。
很简单:根据您的比较,ans
必须同时是 Y
和 N
。