这可能看起来有点愚蠢,但它确实吸引了我。
如果 charString 不包含单词“Hi”,我想抛出一个错误。
所以我写了
if(!charString.contains("Hi"))
/// throw error on screen
现在,要求变了。如果 charString
不包含“Hello”,我也想抛出一个错误。
So, the requirement is I should not throw an error if the
charString
contains either Hi or Hello
所以我写道:
if(!charString.contains("Hi") || !charString.contains("Hello"))
/// throw error on screen
令我震惊的是,我意识到我在编写上述代码时大错特错。那我怎么能把它写在一个单独的 if 语句中呢?
要求是:
"If charString contains either Hi or Hello, do not throw error"
最佳答案
一个非常清晰的方法(以需要注释的多余 block 为代价)是写
if (charString.contains("Hi") || charString.contains("Hello")){
// do nothing
} else {
// throw an error
}
这相当于少了眉毛
if (!(charString.contains("Hi") || charString.contains("Hello"))){
// throw error
}
或(由于德摩根定律 https://en.wikipedia.org/wiki/De_Morgan%27s_laws )
if (!charString.contains("Hi") && !charString.contains("Hello"))){
// throw error
}
关于java - 在 java 中使用 if 和逻辑 OR 在任一条件之间进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40525432/