Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Trying to understand boolean and while loop

 
Gerald.M Beiles
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The method is demonstrating the use of a boolean and a while loop. The method will search through a collection of notes and see if the entered string is found. The method is listed below



My main problem is with the boolean variable and the while loop. My understanding is that the while loop should only execute if the index is less than the size of the notes in the class and "found" variable is true. The first condition will be true but the second one doesnt evaluate to true so wouldn't the whole condition evaluate to false and cause the while loop to never execute. Thanks for any help you might be able to offer. I know it must be simple but I can't get my head around the problem.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you missed a sneaky punctuation mark.

The exclamation point reads "not" out loud and reverses the following boolean. So !found reads "not found" and is true when found is false. It loops while not found and stops when found (is true)
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your condition includes "!found". That "!" means "not"; so it's "while not found" -- i.e., "while found is false, do this..." so setting found to true stops the loop.
 
Jinny Morris
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gerald -

Your loop condition is:


The ! symbol in front of found needs to be read as "not"; if "not found" is true, then "found" must be false.

So your loop should continue while (index < notes.size()) evaluates "true" and not found evaluates "true" (which means that found evaluates as false).

The negations can be tricky, especially when combined with other conditions.

Have fun!
 
fred rosenberger
lowercase baba
Bartender
Posts: 12146
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OH, wait... I know... the "!" in front of...

ah, shoot. nevermind.

:-)
 
Gerald.M Beiles
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks everyone for the help. I drift in and out of trying to keep the ! not operator straight in my head. I'll print this out and keep it handy.

Thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic