Java做while循环使字符串测试行为不同 [英] Java do while loop making string testing act differently
问题描述
我对使用||的行为感到非常困惑.equals函数的运算符。有没有理由我不能在字符串或其他东西上使用它?
I am very confused at the behavior of using the || operator on the .equals function. Is there a reason I can not use it on strings or something?
这是有效的:
do{
System.out.println("Play again? [Y/N]");
//input: Y
play = in.nextLine();
play = play.toUpperCase();
}
while(!"Y".equals(input) ); //breaks out of loop (as it should)
为什么这不起作用?!
do{
System.out.println("Play again? [Y/N]");
//input: Y
play = in.nextLine();
play = play.toUpperCase();
}
while( !"Y".equals(input) || !"N".equals(input) ); //infinite loop
推荐答案
让我们把它说成文字。
吃掉所有这些水果,只要它不是苹果或它不是橙子。
"Eat all of this fruit as long as it's not an apple OR it's not an orange."
- 草莓:不是苹果,继续。
- 香蕉:不是苹果,继续。
- 橙色:不是苹果,所以......继续。
- Apple:是苹果;但实际上不是橙色,所以...继续...... :(
- Strawberry: not an apple, continue.
- Banana: not an apple, continue.
- Orange: not an apple, so... continue.
- Apple: is apple; but is actually not an orange, so... continue...... :(
如果它是苹果,不是一个橙色将是真的;如果它是一个橙色,不是一个苹果将是真的;如果它是一个奇异果,两者都将是真的。没有办法停止进食(除非你爆炸或陷入昏迷)。
If it's an apple, "not an orange" will be true; if it's an orange, "not an apple" will be true; if it's a kiwi, both will be true. There is no way to stop eating (unless you explode or crash into a coma).
错误的逻辑会导致人们死于水果。
Bad logic leads people to death by fruit.
你想要吃掉所有这些水果,只要它是不是苹果,也不是橙子。
You want "eat all of this fruit as long as it's not an apple AND ALSO not an orange".
这篇关于Java做while循环使字符串测试行为不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!