在if-else中初始化String变量

时间:2014-10-28 21:24:15

标签: java if-statement initialization

我正在尝试在这里写一个程序,在我的if-else语句中,我String messageToStudent初始化if taskCompleted == 'y' || taskCompleted == 'Y',并在我的else语句中初始化它用于其他任何事情。但是,当我尝试编译它时,messageToStudent可能尚未初始化。现在,我以为我通过代码完成了messageToStudent字符串中的一个会初始化,但我想我错了。这是我到目前为止所做的:

if(school == 1) {
    System.out.println(name + ", have you started your engineering project yet?");
    taskCompleted = scan.nextLine().charAt(0);
    if (taskCompleted == 'y' || taskCompleted == 'Y')
        messageToStudent = "Good for you! Keep me updated on your progress.";
    System.out.println(messageToStudent);
} else {
    messageToStudent = "That's not good at all. It's nearly November!";
}
System.out.println(messageToStudent);

1 个答案:

答案 0 :(得分:2)

如果school1taskCompleted不是'y''Y',该怎么办?这是messageToStudent未初始化的路径。

提供一个值,即使它是一个空字符串或顶部的null,所以它总是被初始化。