PDA

View Full Version : Help with java, while loop




crazykid888
Oct 18, 2010, 08:33 PM
I am getting an error for this ,
while(word != dog) {

}

i want to tell the user that if they type dog the loop will quit,
but the compiler is giving me an error. cannot find symbol for dog. why is this happening.
i thought the condition could be anything and im getting so confused!!!
thanks



sammich
Oct 18, 2010, 08:37 PM
while (word != "dog") {
}

The compiler is looking for a variable named 'dog', instead of the string "dog".

crazykid888
Oct 18, 2010, 08:46 PM
then how do i get it to work if i want the while loop but i dont want the loop to run if the user types dog? cause it wont let me put anything in there because i always get a variable error. ??!?!?

sammich
Oct 18, 2010, 09:30 PM
Did you try the code:

while (word != "dog") {
}

samwich
Oct 18, 2010, 09:48 PM
I thought with strings you had to use the .equals method so:


while(!word.equals("dog")){

}

although, it has been awhile since I've worked with Java

lee1210
Oct 18, 2010, 09:48 PM
Comparing pointers won't work. Use .equals.

-Lee

sammich
Oct 18, 2010, 10:00 PM
I'm sure that works in Java? At least it works in Python, which I've spent the last few months in...

robbieduncan
Oct 19, 2010, 04:07 AM
I'm sure that works in Java? At least it works in Python, which I've spent the last few months in...

It might work in Java if both strings have been interned (the static "dog" will have the variable might or might not). In general, unless you can be 100% sure, you should not compare two objects for content equality using pointer comparison.

Littleodie914
Oct 19, 2010, 07:54 AM
I thought with strings you had to use the .equals method so:


while(!word.equals("dog")){

}

although, it has been awhile since I've worked with JavaThat's close to a good solution, but would be better written as:

while(!"dog".equals(word))

This will not throw a NullPointerException, whereas the quoted solution would if word was null.

An even better (see: best) solution would be to use a utility function, found in something like the Apache Commons library:

while (!StringUtils.equals("dog", word))

yg17
Oct 20, 2010, 08:58 AM
It might work in Java if both strings have been interned (the static "dog" will have the variable might or might not). In general, unless you can be 100% sure, you should not compare two objects for content equality using pointer comparison.

This. I can't think of a reason to ever do (string1 == string2) even if they're both static. For clarity, always use the equals method.