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條件中做一個關於做賦值的重要警告。忽略這些警告是引入錯誤的絕對方法,特別是作爲初學者。 –