0

Sorry guys I just have a quick question. I am trying to figure out why program won't print out "Your item is a moose" when the user enters animal at the first prompt and then puts yes at the second prompt. Any help would be great thanks

    public static void main(String[] args) {
    // TODO Auto-generated method stub


    String Answer1;
    String Answer2;

    // Read in how much cash the user has
    Answer1 = JOptionPane.showInputDialog("Question 1: Is it an animal, vegetable, or mineral");
    Answer2 = JOptionPane.showInputDialog("Question 2: Is it bigger than a breadbox");


    if (Answer1 == "animal" && Answer2 == "yes") {
        JOptionPane.showMessageDialog(null, "Your item is: A Moose");
    }
}

}

2 Answers2

0

In Java, you wouldn't compare strings with the double equal symbol, it just for integers. You would do it using the method equals or equalsIgnoreCase to compare strings doesn't matter if there are in Upper Case or not.

if (Answer1 == "animal" && Answer2 == "yes") {
        JOptionPane.showMessageDialog(null, "Your item is: A Moose");
    }

So, in your case, you can use equals

if (Answer1.equals("animal") && Answer2.equals("yes")) {
        JOptionPane.showMessageDialog(null, "Your item is: A Moose");
    }
Kenry Sanchez
  • 1,703
  • 2
  • 18
  • 24
-1

You can't use the == conditional operator for Strings in Java because they are Objects.

When you use == for Objects, it compares the value of their address instead of the actual value.

Instead use

Answer1.equals("animal") && Answer2.equals("yes")

in your condition.

Martin Navarro
  • 574
  • 4
  • 10