0
public class ex1 {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("Please enter a series of strings each followed by the enter key. When you'd like to end thr program simply type 'quit': \n");
    Scanner scan = new Scanner(System.in);

    ArrayList<String> inputList = new ArrayList<String>(); // creates a list to store user input

    String input = scan.nextLine(); //takes the scanner input
    while(input != "quit") { //makes sure its not equal to quit
        //System.out.println(input);
        inputList.add(input);
        input = scan.nextLine();
    }
    scan.close();       
    System.out.println("The number of strings enetered was: " + inputList.size());
    System.out.println("The strings you entered were as follows");
    for (String i: inputList) {
        System.out.println(i);

    }

} }

I'm trying to use the preceding code to take a series of inputs from a user using the enter key and if they enter quit I end the program. However the condition is never satisfied and the while loop never ends and I can't understand why

KONADO
  • 189
  • 1
  • 13

2 Answers2

1
 while(!input.equals("quit")) { //makes sure its not equal to quit
        //System.out.println(input);
        inputList.add(input);
        input = scan.nextLine();
    }

You should use equals method as shown above to compare strings. Java provides equals method to compare the contents of two strings. == and != operators are used in comparing object equalities.

sakthisundar
  • 3,278
  • 3
  • 16
  • 29
0

a == b returns true if, and only if, a points to the same object as b

The equals method should be used, as the String class implements it so that, if a contains the same characters as b, it would returns true.

while (!input.equals("quit")) { ... }
Justin Cadou
  • 11
  • 1
  • 5