gpt4 book ai didi

java - 你能解释一下这个使用枚举的java程序的输出吗?

转载 作者:行者123 更新时间:2023-12-01 18:25:36 26 4
gpt4 key购买 nike

class Ideone
{
enum Members{
A(1),B(2),C(3); // I have 3 enum constants here
private int size;
Members(int size){
//System.out.println("Initializing var with size = "+size);
}
}
public static void main (String[] args) throws java.lang.Exception
{
System.out.print("main ");
// your code goes here
for (Members i: Members.values()){
System.out.print(i.name());
System.out.println(i.size);
}
}
}

这是程序的输出-

主要A0
乙0
C0

为什么尺寸值不打印为 1、2 和 3,而是打印为 0?

最佳答案

因为你没有映射size属性。将枚举构造函数更改为:

Members(int size){
this.size = size;
}

顺便说一句:您应该始终将枚举字段标记为final,因为枚举只存在一次(单例)。因此将 private int size 更改为 private Final int size

关于java - 你能解释一下这个使用枚举的java程序的输出吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26324931/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com