-1

I am trying to write a program where I get a userInput and keep getting the userInput until the user enters "quit". However, the while loop does not stop even though I enter quit. I thought it has to do something with the nextLine() function but not sure. I would appreciate your help.

Here's the code below: (I have java.util.Scanner imported)

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a string: ");
        String userInput = in.nextLine();
        while (userInput != "quit" ){
            System.out.println("Hello World");
            userInput = in.nextLine();
        }
        System.out.println("Never reaches here");
    }
}
Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60

1 Answers1

3

Use .equals() to compare Strings:

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a string: ");
        String userInput = in.nextLine();
        while (!userInput.equals("quit")) {
            System.out.println("Hello World");
            userInput = in .nextLine();
        }
        System.out.println("Never reaches here");
    }
}
Spectric
  • 30,714
  • 6
  • 20
  • 43