user2113591
user2113591

Reputation: 19

Scanner nextLine() doesn't seem to change string

So my problem is I'm trying to make a very simple program to refresh my terrible coding skills, but I've run into a problem I don't understand. The program is supposed to take the answer "Yes" and print "yay", just to check if it worked, but it doesn't work. So I'm wondering what I'm doing wrong.

public class main {
    /**
     * @param args
     */
    public static void main(String[] args) {
        int playerTroops, computerTroops;
        String teamName, computerName = "Orcs", answer;
        Scanner listener = new Scanner(System.in);
        System.out
                .println("Welcome to the Battle Grounds, where you are responsible for winning a war \nAre you ready? \nYes or No");
        answer = listener.nextLine();

        if (answer == "Yes")
            System.out.println("Yayy");
        else
            System.out.println("Why");
    }
}

Upvotes: 0

Views: 524

Answers (1)

TtT23
TtT23

Reputation: 7030

For Java String comparison, you must use the .equals operator:

if(answer.equals("Yes"))

If you want to ignore case,

if(answer.equalsIgnoreCase("Yes"))

In Java, the operator == checks for reference equality. Under normal circumstances, equal strings don't automatically have same reference (I.E: They are different objects. This distinction is utterly important in Java).

Upvotes: 4

Related Questions