简体   繁体   English

.equals 与其他布尔函数

[英].equals with other Boolean functions

In a small segment of my program I'm trying to validate if someone enter M,m,F,f and for the most part I got it, but something seems wrong when I put the statements together.在我的程序的一小部分中,我试图验证是否有人输入了 M、m、F、f 并且在大多数情况下我得到了它,但是当我将这些语句放在一起时似乎有些错误。 For example,例如,

   String _gender = "M";
   if(!"m".equals(_gender.toLowerCase())||!"f".equals(_gender.toLowerCase())){
      System.out.println("try again");
   }else 
      System.out.println("success");

It tells me to try again, but when I put it as:它告诉我再试一次,但是当我把它写成:

  String _gender = "M";
   if(!"m".equals(_gender.toLowerCase())){
      System.out.println("try again");
   }else 
      System.out.println("success");

It gives me a success.它给了我一个成功。 I don't know if its something with how I'm using the or, but thats what I've guessed.我不知道这是否与我使用 or 的方式有关,但这就是我的猜测。 I also think it may be something to do with the fact that the check is checking both or something.我还认为这可能与支票同时检查两者或某事的事实有关。 Idk I've been at this for a while and its been confusing me. Idk 我在这方面已经有一段时间了,这让我感到困惑。

There is logical mistake.有逻辑错误。 It should go into "try again" when both equal() results are false.当 equal() 结果都为假时,它应该进入“再试一次”。

String _gender = "M";
if(!"m".equals(_gender.toLowerCase()) && !"f".equals(_gender.toLowerCase())){
  System.out.println("try again");
}else 
  System.out.println("success");

Let's evaluate your code:让我们评估您的代码:

String _gender = "M";
if(!"m".equals(_gender.toLowerCase())||!"f".equals(_gender.toLowerCase()))

if(!true || !false) => if(false || true) => true if(!true || !false) => if(false || true) => true

Now you understand the reason why you got the output, try again .现在您了解了获得输出的原因,请try again

Now, let's fix it:现在,让我们修复它:

Do it as这样做

String _gender = "M";
if (!("m".equals(_gender.toLowerCase()) || "f".equals(_gender.toLowerCase()))) 

which evaluates to if (!(true || "f".equals(_gender.toLowerCase()))) => (!(true)) => false其计算结果为 if (!(true || "f".equals(_gender.toLowerCase()))) => (!(true)) => false

which will give you the intended output, success这将为您提供预期的输出, success

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM