1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

Help with java, while loop

Discussion in 'Mac Programming' started by crazykid888, Oct 18, 2010.

  1. macrumors newbie

    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!!!
  2. macrumors 601


    while (word != "dog") {

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

    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. ??!?!?
  4. macrumors 601


    Did you try the code:

    while (word != "dog") {
  5. macrumors regular

    I thought with strings you had to use the .equals method so:



    although, it has been awhile since I've worked with Java
  6. macrumors 68040


    Comparing pointers won't work. Use .equals.

  7. macrumors 601


    I'm sure that works in Java? At least it works in Python, which I've spent the last few months in...
  8. Moderator


    Staff Member

    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.
  9. macrumors 68000


    That's close to a good solution, but would be better written as:

    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))
  10. macrumors G5

    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.

Share This Page