我想知道什麼是錯的:這有什麼不對?
if (q == "outside" && q1 == "not alive") {
System.out.println("bison");
}
這種說法完美的作品:
if (q == "outside" && q1 == "alive") {
System.out.println("bison");
}
所有的如果包含語句「活着」的作品完美,但包含的語句所有如果「不活着」不起作用。
這是一個鍛鍊,我有沒有使用否則,如果要不要做。
全碼: -
import java.util.Scanner;
class age04 {
public static void main(String [] args) {
Scanner keyboard = new Scanner(System.in);
String q, q1,;
System.out.println("Two more questions, baby!");
System.out.println("Think of something and i'll try to guess it!");
System.out.println("Question 1) Does it stay inside or outside or both");
q = keyboard.next();
System.out.println("Question 1) Is it alive?");
q1 = keyboard.next();
if (q == "inside" && q1 == "alive") {
System.out.println("houseplant");
}
if (q == "inside" && q1 == "not alive") {
System.out.println("shower curtain");
}
if (q == "outside" && q1 == "alive") {
System.out.println("bison");
}
if (q == "outside" && q1 == "not alive") {
System.out.println("bison");
}
if (q == "both" && q1 == "alive") {
System.out.println("dog");
}
if (q == "both" && q1 == "not alive") {
System.out.println("cell phone");
}
}
}
你正在做一個普通的Java初學者的錯誤,那就是用'=='比較字符串。您應該使用'.equals(...)'代替。 – Jesper