Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

crazykid888

macrumors newbie
Original poster
Aug 4, 2010
25
0
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
 
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. ??!?!?
 
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
 
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.
 
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
That's close to a good solution, but would be better written as:

Code:
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:

Code:
while (!StringUtils.equals("dog", word))
 
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.