permaculture playing cards*
The moose likes Beginning Java and the fly likes While loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "While loop" Watch "While loop" New topic
Author

While loop

Atah Tabotnjap
Greenhorn

Joined: Mar 17, 2008
Posts: 24
Can someone please help debug this piece of code. The statement block when the while expresssion resolves to true is never executed, no matter what i type in:
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3647
    
  16

So how do you know it evaluates to true?
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7824
    
  21

Atah Tabotnjap wrote:Can someone please help debug this piece of code.

Actually, that's your job. What we're happy to do is point you in the right direction, and my first one is that, when you're debugging, System.out.println() is your friend.

So, what about adding:
System.out.println(choice==option);
immediately before your 'while' loop for starters?

That might give you some interesting information.

Winston

PS: Please UseCodeTags (←click) when you post code. I've added them for you this time - see how much better it looks? And please read the link carefully, because your indenting is a bit excessive.

Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14157
    
  19

You should not use == to compare strings. Use .equals(...) instead.

The == operator compares object references. The result of comparing two references will only be true when the two references on the left and right side of the == refer to the exact same object. If you have two String objects with the same content, then the result will be false, because you have to distinct String objects.

So, you'll need to use:

Note that you will probably have to add null checks as well, because if 'choice' is 'null' you will get a NullPointerException if you try to call a method such as equals on it.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Atah Tabotnjap
Greenhorn

Joined: Mar 17, 2008
Posts: 24
I still don't understand why it is not working. When i try to print both String variables as follows:



i get:

hit
hit
false.

hit and hit are equal, while does it then evaluate to false.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7824
    
  21

Atah Tabotnjap wrote:hit and hit are equal, while does it then evaluate to false.

Because you haven't read the AvoidTheEqualityOperator page.

'hit' and 'hit' (or rather, two String objects containing those characters) are equal(), but they're NOT necessarily '=='.

Winston
Atah Tabotnjap
Greenhorn

Joined: Mar 17, 2008
Posts: 24
Thanks man !
 
 
subject: While loop