[英]Why is Java forcing me to initialize my String before letting the user input the value of the String?
I'm essentially making a small, simply "twenty questions" style program, using nested if-statements to try to guess what object the user is thinking based on clarifying questions.我基本上是在制作一个小型的、简单的“二十个问题”风格的程序,使用嵌套的 if 语句来尝试猜测用户在澄清问题的基础上在想什么 object。 I'm using the if statements to eventually give the user a "result" at the end, using a String variable called "result".
我使用 if 语句最终在最后给用户一个“结果”,使用一个名为“result”的字符串变量。
My ultimate confusion lies in which the compiler is stating that " variable response may have not been initialized
".我最终的困惑在于编译器声明“
variable response may have not been initialized
”。 To which, based on the code, I would think it is after the if statements.根据代码,我认为它在 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.");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.