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

时间:2015-09-14 21:14:15

标签: java if-statement nested java.util.scanner

这是一个简单的程序,要求用户提出两个问题。根据用户的输入,我们将显示对象是什么的猜测。类似于游戏" 20个问题"。无论我给程序输入什么,它总是返回myGuess的值为"回形针"

我已经尝试注释掉每个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);
      }
  }

1 个答案:

答案 0 :(得分:0)

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

更改此

     if (input1 == "animal")

    if(input1.equals("animal"))

看看这个link