如果我理解正确,您只想有 1 个变量来存储所有元素及其质量,在这种情况下,我建议使用 HashMap。它不会真正节省代码行,但会让你很容易地完成第 2 点。HashMaps 存储一组键值对,如果您有键,您可以获得值,因此这将创建列表:
//Declare a new hashmap and initialize it
HashMap<String, Integer> elements = new HashMap<>();
//Add element information
elements.put("CARBON", 12);
elements.put("OXYGEN", 16);
elements.put("HYDROGEN", 1);
elements.put("SULFUR", 32);
然后例如要从对话框中获取用户输入并将结果打印到命令行,您可以执行以下操作:
//Collect user input and convert it to all upper case (in real life you would validate this)
String input = JOptionPane.showInputDialog(null, "Please enter an element name").toUpperCase();
//If element name exists in hashmap print its atomic weight
if(elements.containsKey(input.toUpperCase())){
System.out.println("Atomic Weight: " + elements.get(input));
}