为什么Java强制我在让用户输入String的值之前初始化String



我本质上是在做一个小的,简单的"二十个问题";风格程序,使用嵌套的if语句,试图在澄清问题的基础上猜测用户在想什么对象。我使用if语句来最终给用户一个";结果";最后使用一个名为";结果";。

我的最终困惑在于编译器声明";variable response may have not been initialized";。根据代码,我认为是在if语句之后的

import java.util.Scanner;
public class TwoQuestions {
public static void main (String args[] ) {
Scanner kb = new Scanner(System.in);
String answer1, answer2, response;
System.out.println("n[Two Questions]nThink of an object, and I'll try to guess it.");
System.out.println("Is it an "animal", a "vegetable", or a "mineral"? (Type an answer exactly as quoted)");
answer1 = kb.nextLine();
System.out.println("Is it bigger than a breadbox? (yes/no)");
answer2 = kb.nextLine();
// example "response" based on user decisions
if (answer1 == "animal" || answer1 == "Animal") {
response = "yes";
if (answer2 == "yes" || answer2 == "Yes") {
response = "squirrel";
}
}
// more if statements...
// final machine "response" to user"
// TODO: Figure out why *this* "response" requires initialization before if statements.
System.out.println("My guess is that you are thinking of a " + response + ".nI would ask you if I'm right, but I don't actually care.");
}
}
  1. 就像疯狂的程序员说的那样,使用Stringequals函数来比较字符串
  2. 是的,在进行编译之前需要对其进行初始化。如果我没有错,你可以用Null初始化,或者"&";,空字符串

最新更新