gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:25:47 25 4
gpt4 key购买 nike

继续 this post我一直在研究和弄乱枚举,现在我已经设法创建一个枚举来保存我想要的值并以我想要的方式输出它们,现在我只想知道我怎么能获得相同的输出,但针对单个项目而不是每个项目。同样,我是 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);
}
}
}

最佳答案

您可以使用传入用户输入的 valueOf 方法来检索枚举:

Element ele = Elements.valueOf(input);

然后您可以使用打印语句打印信息:

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

输出:

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

关于java - 如何获取 Java 枚举数组中特定项的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53329907/

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