繁体   English   中英

为什么字节参数不能识别为整数?

[英]Why aren't byte arguments recognized as integers?

我有以下枚举:

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

尽管我传递了有效的字节参数,但它给我一个错误,提示“构造函数Months(int)未定义” 我究竟做错了什么?

最简单的解决方案是接受一个int

private Months(int numberOfDays){
    this.DAYS = (byte) numberOfDays;
}

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);
} 

这些数字是int文字。 您必须将它们强制转换为byte

 JAN((byte)31),

Java语言规范对词法整数文字说了以下内容:

文字的类型确定如下:

  • 以L或l结尾的整数文字(§3.10.1)的类型很长(§4.2.1)。
  • 任何其他整数文字的类型为int(第4.2.1节)。

因此,它要求您将此整数文字显式转换为字节。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM