Java do while loop making string testing act differently

懵懂的女人 提交于 2019-11-29 13:20:11

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

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

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.

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