-4

I have a simple code in java that always returns "Game over.".

import java.util.Scanner;
public class nextQuestion {
    public void newQuestion() {
        Scanner choice2 = new Scanner(System.in);
        System.out.println("What is my name?");
        System.out.println("A. Mark");
        System.out.println("B. Robert");
        System.out.println("C. Mio");
        System.out.println("D. Samantha");
        String answer2 = choice2.nextLine();
        if(answer2 == "a" || answer2 == "A") {
            System.out.println("Game over.");
            System.exit(0);
        } else if(answer2 == "b" || answer2 == "B") {
            System.out.println("Nice guess!");
            System.exit(0);
        } else if(answer2 == "c" || answer2 == "C") {
            System.out.println("Game over.");
            System.exit(0);
        } else if(answer2 == "d" || answer2 == "D") {
            System.out.println("Game over.");
            System.exit(0);
        } else {
            System.out.println("Game over.");
            System.exit(0);
        }
    }
}

However if I use switch statement, it does work. What is the problem with this?

Filburt
  • 17,626
  • 12
  • 64
  • 115
wobsoriano
  • 12,348
  • 24
  • 92
  • 162

1 Answers1

2

Do not use "==" to compare string it is not viable, you should use if answer2.equals("a") == tests for reference equality. .equals() tests for value equality. Consequently, if you actually want to test whether two strings have the same value you should use .equals(). There are however a few situations where you can guarantee that two strings with the same value will be represented by the same object because of String interning. Those cases are specified by the Java Language Specification. == is for testing whether two strings are the same object

Anatch
  • 443
  • 1
  • 5
  • 20