Java do while loop making string testing act differently

眉间皱痕 提交于 2019-11-28 06:54:36

问题


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?

this works:

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)

why doesn't this work?!

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

回答1:


Let's put it into words.

"Eat all of this fruit as long as it's not an apple OR it's not an orange."

  • 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".




回答2:


|| means OR.

A || B is true if A is true or B is true.

In your second while loop: !"Y".equals(input) is false because Y is equal to your input. However !"N".equals(input) is true because N is not equal to your input. Hense the whole condition is true, it goes into while loop again.




回答3:


Any Or condition works like this

If first part if true, then second condition is not evaluated If first is false, then second is evaluated If either is true, the result is true.

Now in your case, as input is Y, first condition is false but second is true. Hence the loop evaluates to true.

The while loop will continue till you make the condition false. Hence it continues.



来源:https://stackoverflow.com/questions/39887798/java-do-while-loop-making-string-testing-act-differently

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!