PDA

View Full Version : Why won't this work? (Java)




Hylekmi
Apr 10, 2012, 11:41 PM
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.



macjram
Apr 10, 2012, 11:52 PM
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.

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

lee1210
Apr 10, 2012, 11:54 PM
"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

Hylekmi
Apr 10, 2012, 11:54 PM
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

Your exactly right. Im shot tonight. Eclipse doesn't catch that. thanks

Mac_Max
Apr 12, 2012, 09:06 AM
Your exactly right. Im shot tonight. Eclipse doesn't catch that. thanks

Eclipse won't catch it because its valid Java ;). Sometimes you do want to know if something is at the same address.

robbieduncan
Apr 12, 2012, 10:19 AM
Eclipse won't catch it because its valid Java ;). Sometimes you do want to know if something is at the same address.

Or you might be using interned (http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#intern()) 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).