這是我用Java寫的第二個腳本,因爲我剛剛開始寫一本書,所以我對這個不可避免的荒謬問題表示歉意。字符串沒有在條件聲明?
我正在寫一個腳本,在牆上唱「99瓶啤酒」,並試圖在循環中聲明一個新的String變量。不幸的是,它不會編譯,因爲字符串被認爲是未聲明的。然後,當我將它從條件中拉出時,仍然在循環中,它工作正常。我在這裏錯過了什麼嗎?
工作:
while (beersLeft >= 0) {
String sOrNot = "";
if (beersLeft > 1) {
sOrNot = "s";
} else {
sOrNot = "";
}
System.out.println(beersLeft+" bottle"+sOrNot+" of beer on the wall, "+beersLeft+" bottle"+sOrNot+" of beer!");
System.out.println("Take one down, pass it around, "+beersLeft+" bottle"+sOrNot+" of beer on the wall!");
System.out.println();
beersLeft = beersLeft-1;
}
不工作
while (beersLeft >= 0) {
if (beersLeft > 1) {
String sOrNot = "s";
} else {
String sOrNot = "";
}
System.out.println(beersLeft+" bottle"+sOrNot+" of beer on the wall, "+beersLeft+" bottle"+sOrNot+" of beer!");
System.out.println("Take one down, pass it around, "+beersLeft+" bottle"+sOrNot+" of beer on the wall!");
System.out.println();
beersLeft = beersLeft-1;
}
錯誤:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: <any>
at ch01.BottlesOfBeer.main(BottlesOfBeer.java:21)
上面'if(beersLeft> 1){'put'String sOrNot =「」;'並刪除else語句,閱讀下面的答案爲什麼**爲什麼** – earcam 2013-04-28 01:30:41
哈哈我不需要閱讀爲什麼,作爲一旦你說我在內部面對面,因爲它顯而易見的冗餘。感謝您指出了這一點。 – 2013-04-28 01:34:36
您還必須從'if'中的sOrNot中刪除'String',因爲這仍然會在if範圍內創建名爲sOrNot的第二個變量。 – earcam 2013-04-28 01:37:18