0
我前几天刚开始使用java。我目前正在遵循这个'课程'http://programmingbydoing.com。还没有遇到过任何问题,但但我现在停留在任务32If/else语句
继承人到目前为止我的代码(总是让驼鹿输出,而不是松鼠):
import java.util.Scanner;
公共类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;
公共类Questions32 {
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.");
}
}
请勿将字符串与'=='或'!='进行比较。理解这一点比较*参考* - 两个字符串变量引用相同的String *对象*,这不是你想要的。而是使用执行*功能相等*测试的字符串“equals(...)'或其equals方法(...)' - 字符串具有相同顺序的相同字符 - 这正好你想要什么。 –
同时阅读关于赋值和关系相等的区别。阅读yoda表达的奖金。即使只有凌晨3点的调试会话永久性加强了差异。 – Bathsheba
不确定你使用的IDE是什么,但是你应该在if条件中做一个关于做赋值的重要警告。忽略这些警告是引入错误的绝对方法,特别是作为初学者。 –