Help with java, while loop

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

  1. macrumors newbie

    Joined:
    Aug 4, 2010
    #1
    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
     
  2. macrumors 601

    sammich

    Joined:
    Sep 26, 2006
    Location:
    Sarcasmville.
    #2
    while (word != "dog") {
    }

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

    Joined:
    Aug 4, 2010
    #3
    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

    sammich

    Joined:
    Sep 26, 2006
    Location:
    Sarcasmville.
    #4
    Did you try the code:

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

    Joined:
    Aug 5, 2007
    #5
    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
     
  6. macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #6
    Comparing pointers won't work. Use .equals.

    -Lee
     
  7. macrumors 601

    sammich

    Joined:
    Sep 26, 2006
    Location:
    Sarcasmville.
    #7
    I'm sure that works in Java? At least it works in Python, which I've spent the last few months in...
     
  8. Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #8
    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

    Littleodie914

    Joined:
    Jun 9, 2004
    Location:
    Rochester, NY
    #9
    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))
     
  10. macrumors G5

    yg17

    Joined:
    Aug 1, 2004
    Location:
    St. Louis, MO
    #10
    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