简体   繁体   English

如何在Java中获取枚举数组中特定项目的值?

[英]How to get values for specific items in enum array in Java?

Continuing on from this post I've been looking into and messing around with enums a bit, and now I've managed to create an enum that holds the values I want and outputs them in the way I want, now I'd just like to know how I could get the same output but for a single item rather than every item. 继续从这篇文章开始,我一直在研究和弄乱枚举,现在我设法创建了一个枚举,该枚举包含我想要的值并以我想要的方式输出它们,现在我想知道如何获得相同的输出,但对于单个项目而不是每个项目。 Again, I'm very new to Java so a simple explanation as to how and why would be greatly appreciated. 再说一次,我对Java还是很陌生,所以很简单地解释了如何以及为什么这样做。

public class PeriodicTable {

    public enum Element {
        Lithium("Li", "Alkali Metals", 6.941),
        Iron("Fe", "Transition Metals", 55.933);
        private String symbol;
        private String group;
        private Double weight;

        private Element(String symbol, String group, Double weight) {
            this.symbol = symbol;
            this.group = group;
            this.weight = weight;
        }
    }

    public static void main(String[] args) {
        for(Element cName : Element.values()) {
            System.out.println("Element: " + cName + " (" + cName.symbol + ")" + "\nGroup: " + cName.group + "\nAtomic Weight: " + cName.weight);
        }
    }
}

You can use the valueOf method passing in the user input to retrieve the enum: 您可以使用传入用户输入的valueOf方法来检索枚举:

Element ele = Elements.valueOf(input);

And then you can use your print statement to print the info: 然后,您可以使用打印语句来打印信息:

Element cName = Element.valueOf("Iron");
System.out.println("Element: " + cName + " (" + cName.symbol + ")" + "\nGroup: " + cName.group + "\nAtomic Weight: " + cName.weight);

Output: 输出:

Element: Iron (Fe)
Group: Transition Metals
Atomic Weight: 55.933

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

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