Kar*_*eem 0 java enums byte constructor arguments
我有以下枚举:
public enum Months {
JAN(31),
FEB(28),
MAR(31),
APR(30),
MAY(31),
JUN(30),
JUL(31),
AUG(31),
SEP(30),
OCT(31),
NOV(30),
DEC(31);
private final byte DAYS; //days in the month
private Months(byte numberOfDays){
this.DAYS = numberOfDays;
}//end constructor
public byte getDays(){
return this.Days;
}//end method getDays
}//end enum Months
Run Code Online (Sandbox Code Playgroud)
它给了我一个错误,说"构造函数Months(int)是未定义的",虽然我传递了一个有效的字节参数.我究竟做错了什么?
最简单的解决方案是接受一个int值
private Months(int numberOfDays){
this.DAYS = (byte) numberOfDays;
}
Run Code Online (Sandbox Code Playgroud)
BTW非静态字段应该camelCase不在UPPER_CASE
FEB在某些年份也有29天.
public static boolean isLeapYear(int year) {
// assume Gregorian calendar for all time
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
public int getDays(int year) {
return days + (this == FEB && isLeapYear(year) ? 1 : 0);
}
Run Code Online (Sandbox Code Playgroud)