首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java 區域變數作用域:if 區塊內宣告導致 return 無法存取

     編輯:程式設計綜合問答

錯誤代碼


if (choice.equals("蘋果")) {
    Mobile mobile = new IphoneMobile(material1);
}
if (choice.equals("三星")) {
    Mobile mobile = new SamMobile(material1);
}
return mobile; // 編譯錯誤:mobile 不在作用域內

修正


Mobile mobile = null; // 方法開頭宣告
if (choice.equals("蘋果")) {
    mobile = new IphoneMobile(material1);
} else if (choice.equals("三星")) {
    mobile = new SamMobile(material1);
} else if (choice.equals("小米")) {
    mobile = new MiMobile(material1);
}
return mobile;

原則

  • 區域變數在 **{ }** 區塊內有效,離開區塊即銷毀。
  • 跨 if-else 分支使用時,必須在**共同祖先區塊**(通常是方法開頭)宣告。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved