1

I wrote a simple program which prompts the user to enter a sentence, word, or number, and then prints input is art. I put the program on an infinite loop so that the prompt would repeat. However, now I'm trying to add a way to quit by saying if (input == "quit") break; however it does not seem to be working. It just continues the infinite loop. Here is the full code:

import java.util.Scanner;
public class Art
{
     public static void main(String [] args)
     {
        Scanner input = new Scanner(System.in);
        String a;
       for ( ; ; ) 
            {
            System.out.println("Please enter something: ");
            a = input.nextLine();
            if (a == "quit") break;
            System.out.print("\n");
            System.out.println(a + " is art.");
            System.out.print("\n");


            }
    }
}

Any help would be lovely, thanks!

Calico
  • 57
  • 5

2 Answers2

2

Use input.equals("quit").

The == is used to check whether two objects are the exact same instance - the same thing in memory -which the typed word and the constant string "quit" are not. Two instances of "quit" were created: one typed by the user, and one constant in the program.

The equals() method is used to compare whether two objects are equal in whatever way equality is defined for them. For strings, that would mean having the same text.

The difference between == and equals() is really fundamental in Java, so you should go over it. Here's a good SO post on the topic. Once you start creating your own classes, you will probably be implementing equals() methods for them. For that reason, make sure to go over the equals() / hashCode() contract as well.

Community
  • 1
  • 1
sparc_spread
  • 10,643
  • 11
  • 45
  • 59
1

looks like the a == "quit" is the problem. Compare strings using equals()

if("quit".equals(a)) {

}
Stefan Freitag
  • 3,578
  • 3
  • 26
  • 33
hexbinary
  • 11
  • 3