-1

I am writing a program that takes a user input and depending on their answer gives them a different answer. How do I use a string that the user entered with an if - else statement?

I have this so far:

import java.io.*;
import static java.lang.System.*;

import java.util.Scanner;

class t1_lesson07_template{

     public static void main (String str[]) throws IOException {

              Scanner scan = new Scanner(System.in);

              System.out.print("Hello, welcome to the companion planting guide. ");
              System.out.print("Lets get started! To begin, just input the desired plant in the box to learn what plants to grow with it!");
              String plant = scan.nextLine();
              if (plant == "Asparagus") {
                System.out.print("Tomatoes, parsley, and basil.");
              }


     }

}

I am wondering about the syntax for the if statement in this case.

GrandMasterFlush
  • 6,269
  • 19
  • 81
  • 104

4 Answers4

1

The == operator in Java checks that two references are the same. equals(Object), on the other hand, checks that two references are equal.

In your case, there's no guarantee that the string Asparagus inputed from the user and the hard-coded literal in your code will, in fact, be the same object, so == is wrong, and you should use equals(Object):

if (plant.equals("Asparagus")) {
    System.out.print("Tomatoes, parsley, and basil.");
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

equals

change this plant == "Asparagus"

to

plant.equals("Asparagus")

compare the String with equals();

Nambi
  • 11,944
  • 3
  • 37
  • 49
0

Strings are objects in Java. It is easy to mistake it for a primitive because it is a part of the "default" java.lang class. To compare Strings (as with all objects) you need to use the .equals method.

What the equality operator does in this case is to compare between the addresses of String variable plant and the new String object it allocated just for that line, "Asparagus". Of course, as they are different objects, they will never be equal.

skytreader
  • 11,467
  • 7
  • 43
  • 61
0

"==" -> is just comparasion of the pointers (object reference)

"s1.equals(s2)" -> is the comparasion of the content

Stefan Sprenger
  • 1,050
  • 20
  • 42