0

First off, I know this might have been answered SOMEWHERE but I can't seem to search for the correct terms to get an answer. Also, I'm pretty new to coding, and obvious here, so this probably won't be the best written 'question'.

Quick backstory: I'm coding a sorting game in BlueJ(I know... shitty, but it's what we are learning in school), and for a method I'm creating for any yes/no questions I need isn't working properly. At first, I was having an issue with it allowing to to have the user input save as a String, now I'm having an issue with that String used in the if-else statement parameters. This is what I have right now:

public void userAnswer(int method)                 //used for yes/no questions
{
    System.out.println("Please type 'y' for yes and 'n' for no.");
    String answer = keyboard.next();
    answer.toLowerCase();
    System.out.println(answer + "worked");
    if(answer == "y")
    {
        System.out.println("worked2");
        if(method == 0)
            completeOrNot();
        if(method == 1)
            usersMove(theArray);
    }
    else if(answer == "n")
    {
        System.out.println("worked3");
        System.out.print("\n");
    }
}

I'm completely stuck as to why it's not moving into the if-else statement. I test to see if it would print the String, and it will, but it won't convert it to lower case. I just don't know what to do. Any and all help would be appreciated!

  • I fully accept the marking of this as a duplicate, however I did not realize it was a duplicate because I didn't know I was comparing two Strings. As I stated, I am a noob, and sometimes I forget things/don't know things I should know. So, that being said, I forgot that "y" or "n" was a String. – CrichtonLovesMoya Nov 08 '15 at 04:19

3 Answers3

0

When comparing Strings in Java, use the equals() method. Otherwise, you compare their memory locations if you use ==.

    "hi".equals("hello") returns False
    "hello".equals("hello") returns True
Rahul Syal
  • 13
  • 3
0

Don't use == to compare strings. use equals:

answer.equals("y")
Bon
  • 3,073
  • 5
  • 21
  • 40
0

Strings in Java are objects - you need to evaluate with the equals method for equality, not the == operator for reference identity:

if ("y".equals(answer)) {
    // code
} else if ("n".equals(answer)) {
    // code
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350