0

I am trying to create a simple Scanner test program which will exit once the user inputs "Quit".

I have the variable being output to console and it will output Quit but when I am trying to compare the variable to the raw string it doesn't see it as true.

public static void main(String[] args) {

    String input;
    Scanner sc;

    System.out.println("Enter 'Quit' to exit.");

    while (true) {
        sc = new Scanner(System.in);
        input = sc.nextLine();
        if (input == "Quit") {
            break;
        }
        System.out.println(input);
    }

    sc.close();
}

2 Answers2

1

You need to compare strings with equals()method not with == operator

if (input.equals( "Quit")) {
            break;
        }
Nambi
  • 11,944
  • 3
  • 37
  • 49
1

Use always equals to compare the Strings.

== will compare the references.

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
Gundamaiah
  • 780
  • 2
  • 6
  • 30