【问题标题】:Why aren't byte arguments recognized as integers?为什么不将字节参数识别为整数?
【发布时间】:2013-08-18 13:57:33
【问题描述】:

我有以下枚举:

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) 未定义” 尽管我传递了一个有效的字节参数。 我做错了什么?

【问题讨论】:

  • 你传入的是整数,但你的构造函数需要字节

标签: java constructor enums arguments byte


【解决方案1】:

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

 JAN((byte)31),

【讨论】:

  • 请检查我在对 Peter Lawrey 的评论中提出的问题。
  • 好吧,编译器只是不这样做。它只看到int 文字,并没有进一步查看。
【解决方案2】:

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

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

顺便说一句,非静态字段应该在 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);
} 

【讨论】:

  • @Peter Lawrey 我想过这个问题,但我只是想知道为什么作为参数传递的数字没有被识别为字节而不是整数?
  • 大约 2 月在闰年有 29 天,这是一个特殊情况,所以我只是通过 Months.FEB.getDays() + 1 来处理它;
  • @KareemMesbah 你可以有一个getDays(int year) 方法。
  • 但是isLeapYear() 方法在Months 枚举中丢失了什么?一段不错的代码,但将示例限制在前 3 行会使答案更准确。
  • @KareemMesbah 您可以通过编辑您的问题来澄清您的问题,并添加您关于“我只是想知道为什么作为参数传递的数字不被识别为再见而不是它”的评论。
【解决方案3】:

Java Language Specification 对词法整数文字表示以下内容:

字面量的类型确定如下:

  • 以 L 或 l 结尾的整型文字 (§3.10.1) 的类型是 long (§4.2.1)。
  • 任何其他整型文字的类型都是 int(第 4.2.1 节)。

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

【讨论】:

    猜你喜欢
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 2019-10-23
    相关资源
    最近更新 更多