gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 13:26:47 25 4
gpt4 key购买 nike

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

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

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

关于java - 嵌套 If 语句 - 未收到预期输出 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32574041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com