java 我如何在不写对象名的情况下访问枚举中的对象值?[已关闭]

lokaqttq  于 2022-12-28  发布在  Java
关注(0)|答案(2)|浏览(117)

这个问题似乎与help center中定义的范围内的编程无关。
2天前关闭。
Improve this question

enum Countries{
    France(0 , "hello", "Ch"),
    Germany(1,"hello", "Ch"),
    Georgia(4,"hello", "Ch"),
    Japan(9,"hello", "bu"),
    Thailand(7,"hello", "bu"),
    Russia(5,"hello", "Ch"),
    NewZealand(12,"hello", "Ch"),
    USA(-7,"hello", "mixed");

    public int timezone;
    public String religion;
    public String history;
    Countries(int timezone, String history, String religion){
        timezone = this.timezone;
        history = this.history;
        religion = this.religion;

    }

}

我想通过一个循环访问它们,但我不能这样做,我想访问时区并排序它们,而不需要遍历每个国家(我想在for循环中排序它们)

xyhw6mcr

xyhw6mcr1#

你可以很容易地做到。让我们使用你的枚举。

enum Countries{
    France(0 , "hello", "Ch"),
    Germany(1,"hello", "Ch"),
    Georgia(4,"hello", "Ch"),
    Japan(9,"hello", "bu"),
    Thailand(7,"hello", "bu"),
    Russia(5,"hello", "Ch"),
    NewZealand(12,"hello", "Ch"),
    USA(-7,"hello", "mixed");

    public int timezone;
    public String religion;
    public String history;
    Countries(int timezone, String history, String religion){
        timezone = this.timezone;
        history = this.history;
        religion = this.religion;

    }

    public static void printAllAttributes()
    {

        for (Countries each : Countries.values())
        {

            System.out.println("Name = " + each.name() 
                            + " TimeZone = " + each.timezone
                            + " Religion = " + each.religion
                            + " History  = " + each.history);

        }

    }

}

因为你为你的枚举创建了字段,这意味着你可以在你的枚举中的任何方法中访问它们(因为它们是公共的,这意味着你也可以在其他地方使用这个方法)。
我们所要做的就是创建一个简单的for循环,具体来说就是一个for each循环,然后,我们获取所有字段并打印出来。

ar7v8xwq

ar7v8xwq2#

您的枚举构造函数不正确。您的成员赋值被颠倒了。它需要如下所示。

Countries(int timezone, String history, String religion) {
     this.timezone = timezone;
     this.religion = religion;
     this.history = history;
}

然后添加一个toString方法以便于打印字段。

@Override
 public String toString() {
     return "%s, %d, %s, %s".formatted(this.name(),timezone, history, religion);
 }

然后你可以对数组进行排序并打印出值。Arrays.sort接受一个Comparator作为排序的基础。

Countries[] countries = Countries.values();
 Arrays.sort(countries, Comparator.comparing(c -> c.timezone));
 for (Countries c : countries) {
     System.out.println(c);
 }

印刷品

USA, -7, hello, mixed
France, 0, hello, Ch
Germany, 1, hello, Ch
Georgia, 4, hello, Ch
Russia, 5, hello, Ch
Thailand, 7, hello, bu
Japan, 9, hello, bu
NewZealand, 12, hello, Ch

相关问题