嵌套 If 语句 - 未收到预期输出 Java

Nested If Statement - Not Receiving Expected Output Java

这是一个向用户询问两个问题的简单程序。根据用户的输入,我们将显示对对象是什么的猜测。类似于游戏“20个问题”。无论我给程序什么输入,它总是 returns myGuess 的值是 "paper clip"

我已经尝试注释掉每个 if/else 语句的内部并将输出设置为 1,2,3 但它仍然达到 3(回形针的块)。这让我认为我的字符串比较在用户输入的分配或条件逻辑中存在错误......这是代码:

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);
      }
  }

对字符串使用 .equals() 而不是 == 。 Java 字符串是对象而不是原始数据类型。

改变这个

     if (input1 == "animal")

    if(input1.equals("animal"))

看看这个link