我几天前刚刚开始使用java。我目前正在关注这个课程' http://programmingbydoing.com。还没有遇到任何问题,但现在我陷入了任务32。
到目前为止我的代码(总是得到Squirrel而不是moose作为输出):
import java.util.Scanner;
public class TwoQuestion32 {
public static void main(String[] args) {
boolean animal, vegetable, mineral, smallerthan;
String whatIsIt, biggerThan;
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello and welcome, i've got 2 questions for you!");
System.out.println("Think of an object and i'll try to guess it");
System.out.println();
System.out.println("Question 1) Is it an animal, vegetable or mineral?");
System.out.print(">");
whatIsIt = keyboard.nextLine();
if (whatIsIt == "animal")
animal = true;
if (whatIsIt == "vegetable")
vegetable = true;
if (whatIsIt == "mineral")
mineral = true;
System.out.println("Question 2) Is it bigger than a breadbox?");
System.out.print(">");
biggerThan = keyboard.nextLine();
if (biggerThan == "yes")
smallerthan = false;
if (biggerThan == "no"){
smallerthan = true;}
System.out.print("My guess is that you are thinking of a ");
if (animal = true){
if (smallerthan = true)
System.out.println("squirrel");
}else {
System.out.println("moose");}
}
}
提前致谢!也希望听到如何以更智能的方式提出代码的提示。要友好,请记住我刚刚开始!
编辑:好的,我采取了另一种方法。我的第一次尝试真的很奇怪。谢谢你的帮助!
下面是工作代码:
import java.util.Scanner;
公共课题32 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String whatIsIt, whatIsIt2;
String animal = "animal";
String mineral = "mineral";
String vegetable = "vegetable";
String bigger = "yes";
String smaller = "no";
System.out.println("Hello and welcome, i've got 2 questions for you!");
System.out.println("Think of an object and i'll try to guess it");
System.out.println();
System.out.println("Question 1) Is it an animal, vegetable or mineral?");
System.out.print(">");
whatIsIt = keyboard.nextLine();
System.out.println("Question 2) Is it bigger than a breadbox?");
System.out.print(">");
whatIsIt2 = keyboard.nextLine();
if (whatIsIt.equalsIgnoreCase(animal)){
if (whatIsIt2.equalsIgnoreCase(bigger)){
System.out.println("My guess is that you are thinking of a moose");
}else{ System.out.println("My guess is that you are thinking of a squirrel");
}
}
if (whatIsIt.equalsIgnoreCase(vegetable)){
if (whatIsIt2.equalsIgnoreCase(bigger)){
System.out.println("My guess is that you are thinking of a melon");
}else{ System.out.println("My guess is that you are thinking of a carrot");
}
}
if (whatIsIt.equalsIgnoreCase(mineral)){
if (whatIsIt2.equalsIgnoreCase(bigger)){
System.out.println("My guess is that you are thinking of a Camaro");
}else{ System.out.println("My guess is that you are thinking of a paper clip");
}
}
System.out.println("I would ask you if I'm right, but I dont actually care.");
}
}
答案 0 :(得分:1)
在你的if语句中,每次if (animal = true){
将动物设置为true,而不是检查它(==
)。
另外,对于字符串,您必须使用.equals()
而不是==
。