这是一个简单的程序,向用户询问两个问题。根据用户的输入,我们将显示对对象的猜测。类似于游戏“20个问题”。无论我给程序输入什么,它总是以“回形针”的形式返回myGuess的值。
我试着注释掉每个if/ each语句的内部,并将输出设置为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);
}
}发布于 2015-09-14 21:16:20
字符串使用.equals()而不是==。Java字符串是对象,而不是原始数据类型。
改变这个
if (input1 == "animal")至
if(input1.equals("animal"))看看这个link
https://stackoverflow.com/questions/32574041
复制相似问题