简体   繁体   English

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

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

I have the following enum: 我有以下枚举:

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

It gives me an error that says "The constructor Months(int) is undefined" although I am passing a valid byte arguments. 尽管我传递了有效的字节参数,但它给我一个错误,提示“构造函数Months(int)未定义” What am I doing wrong? 我究竟做错了什么?

The simplest solution is to accept an int value 最简单的解决方案是接受一个int

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

BTW non-static fields should be in camelCase not UPPER_CASE BTW非静态字段应该在camelCase而不是UPPER_CASE

Also FEB has 29 days in some years. 此外,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);
} 

Those numbers are int literals. 这些数字是int文字。 You'd have to cast them to byte : 您必须将它们强制转换为byte

 JAN((byte)31),

The Java Language Specification says the following regarding lexical integer literals: Java语言规范对词法整数文字说了以下内容:

The type of a literal is determined as follows: 文字的类型确定如下:

  • The type of an integer literal (§3.10.1) that ends with L or l is long (§4.2.1). 以L或l结尾的整数文字(§3.10.1)的类型很长(§4.2.1)。
  • The type of any other integer literal is int (§4.2.1). 任何其他整数文字的类型为int(第4.2.1节)。

So it requires you to explicitly cast this integer literal to byte. 因此,它要求您将此整数文字显式转换为字节。

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

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