java循环实验,Java做while循环使字符串测试行为不同

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

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值