Reputation: 11
I am creating a program in netBeans that takes user input of an elemental symbol and uses the atomic mass of that element. I declared all the elements as constants with their atomic mass, but realized I do not know of a way of getting the user input to connect with them. I'd rather not make if statements over 100 times.
Upvotes: 1
Views: 86
Reputation: 37950
A HashMap
is a way to map keys of any one type you choose to values of any one (possibly different) type you choose.
HashMap<String, Double> atomicMasses = new HashMap<String, Double>();
atomicMasses.put("H", 1.008);
atomicMasses.put("He", 4.002602);
// And so on...
String symbol = ...; // Acquire symbol string somehow
if (atomicMasses.containsKey(symbol)) {
System.out.println(atomicMasses.get(symbol));
}
The first generic type is the key type; the second is the value type. put()
creates a mapping; containsKey()
checks whether a mapping for the given key is present (note that this is case sensitive, so looking for "h"
won't work); and get()
gets the value that is connected to the given key (also case sensitive).
Since HashMap
implements the more generic interface Map
and the interface contains all of the operations you normally need to do, it is customary to write the declaration as Map<String, Double> atomicMasses = new HashMap<String, Double>();
.
Upvotes: 1