2014-10-28 27 views
0

我想在這裏寫一個程序,並在我的if-else語句中我有String messageToStudent初始化如果taskCompleted == 'y' || taskCompleted == 'Y',並在我的else語句中初始化它的其他任何東西。但是,當我嘗試編譯它時說messageToStudent可能尚未初始化。現在,我認爲我通過代碼中的一個messageToStudent字符串將初始化,但我想我錯了。這是我到目前爲止有:初始化字符串變量在if-else

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); 
+0

編譯器不夠智能。在聲明變量時,給它一個初始值''「'或'null'。 – 2014-10-28 21:26:07

+1

如果school是'1'而taskCompleted是'N',那麼messageToStudent'初始化在哪裏? – azurefrog 2014-10-28 21:26:12

+0

你應該閱讀[NullPointerException](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – gudthing 2014-10-28 21:27:50

回答

2

如果school1taskCompleted不是'y''Y'?這是messageToStudent未初始化的路徑。

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