Pages: [1]   Go Down
Author Topic: Boolean Operators..&& (AND) is working but ! (NOT) is'nt working  (Read 486 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Full Member
***
Karma: 1
Posts: 179
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi there,
I'm trying to use NOT but unfortunately even with the codes below, arduino never gets into the second if.
Code:
if((readString.indexOf("test") >0) && (readString.indexOf("test2") >0))
 {
   //1  
 }//checks for test words

  if((!readString.indexOf("test") >0) && (!readString.indexOf("test2") >0))
{  
   //2  
  }  //check if there aren't any test words

No1 is working like a charm but No2 isn't for some reason.
When I check for 1, I type "test" and "test2", but when I check for 2 I type other words. It never gets into 2.
Can anyone explain to me why this is happening?

 
« Last Edit: December 01, 2012, 09:30:50 pm by nathanas » Logged

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 601
Posts: 48543
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

You are applying the not to the wrong thing. What you want it !(readString.indexOf("test") >0).

Although, I think that is atrocious code. It's much better to change the value that readString.indexOf() is being compared to, in my opinion.
Logged

0
Offline Offline
Sr. Member
****
Karma: 4
Posts: 323
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
 if((!readString.indexOf("test") >0) && (!readString.indexOf("test2") >0))

See the operator precedence: http://en.cppreference.com/w/cpp/language/operator_precedence

Note that ! is a higher precedence than >.

Consider what happens when we parenthesize by precedence:

Code:
if( !(readString.indexOf("test")) >0 && !(readString.indexOf("test2")) >0 )

PaulS is right too:
Code:
readString.indexOf("test")) <= 0
is a much more readable test and faster to type.
Logged

0
Offline Offline
Full Member
***
Karma: 1
Posts: 179
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Thanks for sharing guys!
Made it working.  smiley
Logged

Pages: [1]   Go Up
Jump to: