Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Endless loop !

 
Rahul Sudip Bose
Ranch Hand
Posts: 637
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why does this program not exit when i type n or N ? The program exits when i keep c!='n' in the while loop and enter n while running the program.

 
Matthew Brown
Bartender
Posts: 4566
8
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rahul Sudip Bose wrote:

So you wan't to keep going as long as c isn't equal to 'n' OR c isn't equal to 'N'. Which will always be true, because c can't be both! That should give you a hint.
 
fred rosenberger
lowercase baba
Bartender
Pie
Posts: 12098
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
System.out.println("") is a VERY powerful debugging tool. When I have something like this happen, I liberally stick them in my code. If you think the code should be exiting, print out the value of what you're testing right before you test it...in other words, I would add a line between your current 15 and 16, like



(I print the semi-colon so I know exactly where the variable ends - i.e. I can tell if there are trailing spaces.)

try that, and see what you can figure out.




 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good idea of Fred's. But I shall expand it
 
Rahul Sudip Bose
Ranch Hand
Posts: 637
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Good idea of Fred's. But I shall expand it


The above way is a little difficult for me as of now because I am a beginner. I tried it this way instead :



THE OUTPUT IS :



how do i correct this ?
 
Rahul Sudip Bose
Ranch Hand
Posts: 637
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matthew Brown wrote:
Rahul Sudip Bose wrote:

So you wan't to keep going as long as c isn't equal to 'n' OR c isn't equal to 'N'. Which will always be true, because c can't be both! That should give you a hint.


ahhh ... DOH !!! it works with this simple change :


But i will try it using the != logic also, as an exercise.

Thanks to all.
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
or



. . . while (c != 'n' && c != 'N');
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
De Morgan's Laws

¬a ∧ ¬b ≡ ¬(a ∨ b)
¬a ∨ ¬b ≡ ¬(a ∧ b)

You can use those to swap && and ||
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic