提问人:dissidenttux 提问时间:8/22/2022 更新时间:8/22/2022 访问量:107
为什么 Java 在让用户输入 String 的值之前强制我初始化 String?
Why is Java forcing me to initialize my String before letting the user input the value of the String?
问:
我本质上是在制作一个小型的、简单的“二十个问题”风格的程序,使用嵌套的 if 语句来尝试根据澄清问题来猜测用户在想什么对象。 我使用 if 语句最终在最后给用户一个“结果”,使用一个名为“result”的 String 变量。
我最终的困惑在于编译器声明“”。对此,根据代码,我认为它是在 if 语句之后。variable response may have not been initialized
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赞
Chew Yiwei
8/22/2022
#1
- 就像疯狂的程序员说的那样,使用 String equals 函数来比较字符串。
- 是的,在进行编译之前需要对其进行初始化。如果我没有错,你可以用 Null 或 “ ” 空字符串进行初始化。
评论
0赞
dissidenttux
8/22/2022
太搞笑了!我会偶尔把这个词当作笑话扔给我的伙伴们。
评论
"potato"
response
if
response
else
response
if
String#equalsIgnoreCase
==
String
String#equals