0

This is the first section of my main method, where I prompt the users to input as many phrases as they want, and the input gets saved in an ArrayList. I coded this so that the program would stop asking for more input if the user puts 'q', but for some reason, when I run this, even if I input q, it doesn't exit the loop. It just keeps on asking for more inputs. I'm assuming I made a mistake in the while loop, but I'm not entirely sure what.

I'm really new to Java so I may have made a blatant mistake but I'm not sure..

 public static void main(String [] args)
  {
    //vars
    String userInput;
    int quitter = 0;

    //arraylist
    ArrayList<RecursivePalindrome> a = new ArrayList<RecursivePalindrome>();

    //scanner
    Scanner in = new Scanner(System.in);

    //user input
    System.out.println("\t Palindrome Checker");
    System.out.print("Input phrase one at a time (press 'q' to quit): ");
    while(quitter == 0)
    {

        userInput = in.next();

        if(userInput == "q" )
        {
            quitter++;
        }
        a.add(new RecursivePalindrome( userInput));
        System.out.print("Input phrase one at a time (press 'q' to quit): ");
    }
    System.out.println();
maxitaxi
  • 53
  • 7

2 Answers2

4

Comparison of strings

use .equals

 if(userInput.equals("q"))
        {
            quitter++;
        }
Vinay Veluri
  • 6,671
  • 5
  • 32
  • 56
2

Compare the String with equals() and put break it will exit the while loop

if(userInput.equals("q" ))
        {
            quitter++;
           break;
        }
Nambi
  • 11,944
  • 3
  • 37
  • 49