1

I'm trying to create a program in Java which allows the user to pick from a list of coffees contained in a String array and continues on, but it fails the check and prints out the else statement.

Here is the relevant code:

Scanner scan = new Scanner(System.in);
String[] flavors = {"Black", "French Vanilla", "Hazelnut", "Mango", "Cherokee", "anarcho-syndicalism", "Otis" };

...

System.out.println("Today we have " + Arrays.toString(flavors));
System.out.println("Please enter the name of the coffee you would like exactly as shown above: ");
String coffee = scan.next();

...

for (int i = 0; i < flavors.length; i++) {
    if (coffee == flavors[i]) {
        String selection = flavors[i];

Though not shown here, I believe everything's properly formatted later on in the program. Any ideas?

anc
  • 191
  • 1
  • 19

1 Answers1

3

In general, when comparing objects for equality in java, use .equals(). Use == for comparing primitives. In java, Strings are objects.

change:

if (coffee == flavors[i]) {

to:

if (coffee.equals(flavors[i])) {

When comparing objects with ==, they will only be equal if they are in fact the same instance.

Asaph
  • 159,146
  • 25
  • 197
  • 199