Why won't this work? (Java)

Discussion in 'Mac Programming' started by Hylekmi, Apr 10, 2012.

  1. macrumors regular

    Joined:
    Dec 8, 2010
    #1
    Code:
    public static void playAgain()
    	{
    	Scanner console = new Scanner (System.in);
    	String decision;
    	System.out.println("Do you wish to play again?");
    	decision=console.nextLine();
    	if(decision=="y"||decision=="Y")
    		System.out.println("YES");
    	if(decision=="N"||decision=="n")
    		System.out.println("NO");
    	
    		/*do{outputResults(rollDie());}
    		while(==true);
    		*/
    	}//end playagain
    I get "do you wish to play again" no matter what i enter.
     
  2. macrumors 6502a

    macjram

    Joined:
    Dec 20, 2008
    #2
    I JUST started Java (my 3rd week in lol) but I don't think you can compare strings using == because Strings are references (addresses?) so you're saying

    if ( address1 == address2 )

    I think you can use if (decision.equals("y") || decision.equals("Y"))

    worth a shot until someone more experienced can help ya
     
  3. macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #3
    "Do you wish to play again?" will always display, it's not conditional. Other than that, you're trying to do String comparison with ==, which will only test if that the objects are at the same address. Use .equals to test if the contents are the same instead.

    -Lee
     
  4. thread starter macrumors regular

    Joined:
    Dec 8, 2010
    #4
    Your exactly right. Im shot tonight. Eclipse doesn't catch that. thanks
     
  5. macrumors 6502

    Joined:
    Mar 8, 2004
    #5
    Eclipse won't catch it because its valid Java ;). Sometimes you do want to know if something is at the same address.
     
  6. Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #6
    Or you might be using interned strings which allows this sort of comparison (useful as it saves memory from lots of copies of the same string and allows fast comparison, worth considering if you read lots of strings from a file that might all be the same).
     

Share This Page