在下面的代碼:Java「重複本地變量」 - Java或Eclipse中引發的錯誤?
private static void example() {
String inputString = "test";
switch (inputString) {
case "test":
String outputString = "The string said test";
case "not test":
String outputString = "The string did not say test";
}
/*Do stuff with ouputString*/
}
Eclipse的突出Case "not test"
與錯誤Duplicate local variable outputString
之後的行。但是,由於他們在switch
聲明的獨立分支中,所以它們並不實際發生衝突,因爲一次只能有一個生效。
顯然,在這種情況下,我可以通過移動switch
聲明之外的outputString
聲明來解決問題。但是,在更復雜的程序中,解決方案可能並不那麼簡單。
這是否僅僅是Eclipse引發的錯誤,以防止糟糕的編程技術或實際的Java錯誤?
我對Java很新,很抱歉,如果這是一個新手問題 - 我有一個谷歌的「重複本地變量Java」,但到目前爲止,所有出現的人都在尋求幫助,修復問題(通常的解決方案是重命名其中一個變量),而不是討論問題本身。
要小心,不要使用編譯時錯誤術語「扔」的工作方法。 –
@MarkoTopolnik謝謝,我會研究兩者之間的區別。 – scubbo