简体   繁体   English

在Java中使用if与逻辑OR进行选择

[英]Choose between either condition using if with logical OR in java

This might seems bit foolish, but it has really caught me. 这似乎有些愚蠢,但确实吸引了我。

I want to throw an error if a charString doesn't contain a word "Hi". 如果charString不包含单词“ Hi”,我想抛出一个错误。

So I wrote 所以我写了

if(!charString.contains("Hi"))
   /// throw error on screen

Now, the requirement changed. 现在,要求已更改。 I want to also throw an error if a charString does not contain "Hello". 如果charString不包含“ Hello”,我也想抛出一个错误。

So, the requirement is I should not throw an error if the charString contains either Hi or Hello 因此,要求是,如果我不应该抛出一个错误charString包含Hi 你好

So I wrote: 所以我写道:

if(!charString.contains("Hi") || !charString.contains("Hello"))
   /// throw error on screen

To my horror, I realized I am terribly wrong in writing above code. 令我感到恐惧的是,我意识到编写上述代码是非常错误的。 How can I write it in a single if statement then? 我该如何在单个if语句中编写它呢?

The requirement is: 要求是:

"If charString contains either Hi or Hello, do not throw error" “如果charString包含Hi或Hello,请不要引发错误”

A very clear way (at the expense of a superfluous block that requires a comment) is to write 一种非常清晰的方法(以需要注释的多余块为代价)是编写

if (charString.contains("Hi") || charString.contains("Hello")){
    // do nothing
} else {
    // throw an error
}

This is equivalent to the less eyebrow-raising 这相当于少眉毛

if (!(charString.contains("Hi") || charString.contains("Hello"))){
    // throw error
}

or (due to De Morgan's Law https://en.wikipedia.org/wiki/De_Morgan%27s_laws ) 或(由于De Morgan法则https://en.wikipedia.org/wiki/De_Morgan%27s_laws

if (!charString.contains("Hi") && !charString.contains("Hello"))){
    // throw error
}

As I understand, you want to throw error when it doesn't contain Hi AND doesn't contain Hello . 据我了解,当它不包含Hi且不包含Hello时,您想引发错误。

if(!charString.contains("Hi") && !charString.contains("Hello"))

Your previous code was: 您之前的代码是:

if the String doesn't contain "Hi" or the String doesn't contain "Hello" throw error. 如果字符串不包含“ Hi”或字符串不包含“ Hello”,则抛出错误。 It means that the luck of at least one of those Strings resulted in throwing the error. 这意味着这些字符串中的至少一个的运气导致抛出错误。

Let's describe your flow in plain English: 让我们用简单的英语描述您的流程:

IF charString contains "Hi" or "Hello" (so is a way of saying "Welcome")
    proceed
ELSE
    throw the error.

We can also use the negation: 我们也可以使用否定:

 IF charString doesn't contain one of "Hi" or "Hello" (so is a way of saying "Welcome")
    throw the error
ELSE
    proceed.

In Java they would be: 在Java中,它们将是:

if (charString.contains("Hi") || charString.contains("Hello")) {
    //it's good
} else {
    //it's bad
}

or the second case: 或第二种情况:

    NOT(charString contains Hi or charString contains Hello)
if (!(charString.contains("Hi") || charString.contains("Hello"))) {
    //it's bad
} else {
    //it's good
}

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

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