gpt4 book ai didi

java - 如何使用枚举中的字符串值作为输入来输出 Java 中该枚举项的其余数据?

转载 作者:行者123 更新时间:2023-12-02 01:47:05 26 4
gpt4 key购买 nike

我真的想不出如何表达这个问题,但我有一个相当简单的程序,它会要求用户输入元素周期表中的一个元素,然后输出该元素的符号、族和原子质量。目前它只接受元素名称的输入,我试图让它也接受符号的输入,但我不知道该怎么做。例如,此时如果用户输入“Iron”,程序将正确输出,但如果输入“Fe”,则程序将无法工作。我希望“Fe”的输入也能起作用。我对 Java 非常陌生,因此非常感谢有关如何以及为什么的简单解释。

import java.util.Scanner;
public class PeriodicTable {

public enum Element {
Hydrogen("H", "Nonmetal", "1.008"),
Helium("He", "Noble Gas", "4.003"),
Lithium("Li", "Alkali Metal", "6.941"),
Beryllium("Be", "Alkaline Earth", "9.012"),
Boron("B", "Semimetal", "10.811"),
Carbon("C", "Nonmetal", "12.011"),
//The rest of the periodic table is here, I just removed it for the sake of this post.

private String symbol;
private String group;
private String weight;

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

static Element cName = null;
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter the name of an element in the periodic table. ");
do {
String input = reader.nextLine();
try {
cName = Element.valueOf(input.trim().substring(0, 1).toUpperCase() + input.trim().substring(1).toLowerCase());
} catch(IllegalArgumentException e) {
System.out.println("That name is not valid. Please try again. ");
continue;
}
System.out.println("Element: " + cName + " (" + cName.symbol + ")" + "\nGroup: " + cName.group + "\nAtomic Mass: " + cName.weight);
reader.close();
break;
} while (true);
}
}

最佳答案

集合Element.values()包含枚举类的所有值。
用户提供输入后,循环遍历此集合并检查 symbol 属性以查找元素。

public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
boolean found = false;
do {
System.out.println("Enter the symbol of an element in the periodic table. ");
String input = reader.nextLine().trim();

for (Element e : Element.values()) {
if (e.symbol.equals(input)) {
found = true;
System.out.println("Element: " + e + " (" + e.symbol + ")" + "\nGroup: " + e.group + "\nAtomic Mass: " + e.weight);
}
}
if (!found)
System.out.println("That symbol is not valid. Please try again. ");
} while (!found);
reader.close();
}

关于java - 如何使用枚举中的字符串值作为输入来输出 Java 中该枚举项的其余数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53572352/

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