私があなたを正しく理解しているなら、あなたはすべての要素とそれらの質量を格納するためにただ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));
}