1

This a simple program that asks the user for two questions. Based on the user's input, we will display a guess of what the object is. Similar to the game "20 Questions". No matter what input I give the program, it always returns the value of myGuess as "paper clip"

I have tried commenting out the inside of each if/else statement and having the output set to 1,2,3 but it still gets to 3 ( the block of the paper clip). This leaves me to think that my comparison of strings has a bug either in the assignment of the user input or conditional logic... Here is the code:

import java.util.Scanner;

public class JavaTraining {


  public static void main(String[] args) {

      Scanner keyboard = new Scanner(System.in);
      String input1,input2;
      String myGuess;

      System.out.println("TWO QUESTIONS!");

      System.out.println("Think of an object, and I'll try to guess it.\r\n");

      System.out.println("Question 1) Is it an animal, vegetable, or mineral?");
      input1 = keyboard.nextLine();

      System.out.println("\r\nQuestion 2) Is it bigger than a breadbox?");
      input2 = keyboard.nextLine();

      if (input1 == "animal"){

          if (input2 == "yes"){
              myGuess = "moose";
          }
          else{
              myGuess = "squirrel";
          }
      }
      else if (input1 == "vegetable"){
          if (input2 == "yes"){
              myGuess = "watermelon";
          }
          else{
              myGuess = "carrot";
          } 
      }
      else{
          if (input2 == "yes"){
              myGuess = "Camaro";
          }
          else{
              myGuess = "paper clip";
          } 
      }

      System.out.println("\r\nMy guess is that you are think of a "+myGuess+".\r\nI would"
              +" ask you if I'm right, but I don't actually care."+input1+input2);
      }
  }
Jonathan Scialpi
  • 771
  • 2
  • 11
  • 32
  • @makoto should I delete this question since you have marked it as a duplicate? Or should I leave it since it has a different context and still provides an educational answer? – Jonathan Scialpi Sep 14 '15 at 21:39
  • I don't notice a context; any time someone uses `==` on a String, the answer will generally be the same. It's not a bad question necessarily, but I wouldn't want you to keep it around. – Makoto Sep 14 '15 at 21:47

1 Answers1

0

Use .equals() for strings instead of == . Java strings are objects not primitive data types.

change this

     if (input1 == "animal")

to

    if(input1.equals("animal"))

Take a look at this link

Community
  • 1
  • 1
Amr
  • 792
  • 3
  • 15