2017-02-14 94 views
1

我的類有一個數組作爲其成員之一。在構造函數中,我想將它的成員填充到以下內容中。我該怎麼做,它給了我一個錯誤。聲明後填充數組成員

public class GetCurrentMonth { 

    Calendar now; 
    String[] monthNames; 

    /** 
    * 
    */ 
    public GetCurrentMonth() { 
     now = Calendar.getInstance(); 
     monthNames = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; 
    } 

    public String getMonth() 
    { 
     return monthNames[(now.get(Calendar.MONTH) + 1)]; 
    } 
} 

我不想在構造函數如下添加這些月份的名字,因爲我想跟進良好的編碼習慣,我被告知,所有的初始化應在構造函數中完成。

String[] monthNames = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; 

回答

3

你需要創建一個新的String數組[]

monthNames = new String[] {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; 
4

首先,它不僅是好的做法在構造函數初始化,它實際上是實踐中,由於:

  • 你實際上必須編寫一個構造函數(添加無用代碼)
  • 領域應該是static final,如果他們對每一個實例一樣,就像個月
  • 實例字段應該final如果可能的話,如果有隻有一個方法來初始化它們

最佳實踐的聲明中被初始化,包括堅持命名標準,說你的類應該是這樣的:

public class GetCurrentMonth { 
    private static final String[] MONTH_NAMES = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; 
    private final Calendar now = Calendar.getInstance(); 

    public String getMonth() { 
     return MONTH_NAMES [(now.get(Calendar.MONTH) + 1)]; 
    } 
} 
0

首先,我同意從波希米亞♦答案,但我甚至會更進一步,建議您創建包含您的月份名稱的枚舉。下面是我該怎麼做:

public enum Month { 
    JANUARY("January"), 
    FEBRUARY("February"), 
    MARCH("March"), 
    APRIL("April"), 
    MAY("May"), 
    JUNE("June"), 
    JYLY("July"), 
    AUGUST("August"), 
    SEPTEMBER("September"), 
    OCTOBER("October"), 
    NOVEMBER("November"), 
    DECEMBER("December"); 

    private String displayName; 

    private Month(String displayName) { 
     this.displayName = displayName; 
    } 

    @Override 
    public String toString() { 
     return displayName; 
    } 

    public static Month valueOfIgnoreCase(String value) { 
     return valueOf(value.toUpperCase()); 
    } 
}