Choose between either condition using if with logical OR in java -


this might seems bit foolish, has caught me.

i want throw error if charstring doesn't contain word "hi".

so wrote

if(!charstring.contains("hi"))    /// throw error on screen 

now, requirement changed. want throw error if charstring not contain "hello".

so, requirement should not throw error if charstring contains either hi or hello

so wrote:

if(!charstring.contains("hi") || !charstring.contains("hello"))    /// throw error on screen 

to horror, realized terribly wrong in writing above code. how can write in single if statement then?

the requirement is:

"if charstring contains either hi or hello, not throw error"

a very clear way (at expense of superfluous block requires comment) write

if (charstring.contains("hi") || charstring.contains("hello")){     // nothing } else {     // throw error } 

this equivalent less eyebrow-raising

if (!(charstring.contains("hi") || charstring.contains("hello"))){     // throw error } 

or (due de morgan's law https://en.wikipedia.org/wiki/de_morgan%27s_laws)

if (!charstring.contains("hi") && !charstring.contains("hello"))){     // throw error } 

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -