-1

I'm making a program that find sums multiple values that are in a single string. For example you put H2O in and it will return the molar mass value for that chemical (2*H + O). So I copied the periodic table and listed the values e.g "private double H = 1.008;". So the problem is I need to get that value based on the name of the variable. Here is an example.

private double H = 1.008;

System.out.println(multMass(2, H));
// should print 2.016

public static double multMass(int multiplier, String chem){
    return double(chem) * multiplier;
}              /\ 
               ||
  where the double would go(in this case 'double H')
  • 1
    The Map approach is the best way forward, also use BigDecimal for calculation as double tends to give irrational results, but that is accepted as scientific equations always have the room for a little bit of error – Yugansh May 14 '19 at 00:58
  • I got rid of my dupe suggestion because it was only indirectly answering the question, and wasn't as clear as I originally thought. – Carcigenicate May 14 '19 at 00:59

1 Answers1

1

Don't use raw variables for this. Use a Map instead:

Map<String, Double> elemWeights = new HashMap<>();

// Associate an element symbol and a weight
// This would be your "double H = 1.008"
elemWeights.put("H", 1.008); 
elemWeights.put("Li", 6.94);
...

public static double multMass(int multiplier, String chem) {
    double weight = elemWeights.get(chem); // And do a lookup
    return weight * multiplier;
}  

Or, a little neater:

Map<String, Double> elemWeights = Map.ofEntries(
    entry("H", 1.008),
    entry("Li", 6.94)
    ...
);

Or see here for other ways this can be written based on the version of Java that you're using.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
  • This is close to what OP wants. But I think OP needs to do more work on parsing request and all. – Subir Kumar Sao May 14 '19 at 01:20
  • @SubirKumarSao "So the problem is I need to get that value based on the name of the variable". It seems like they're directly asking about that bit. The rest seems to be a statement regarding their end goal. – Carcigenicate May 14 '19 at 01:51
  • Yes your solution is correct to the question being asked. Sorry If I was not clear. – Subir Kumar Sao May 14 '19 at 02:58
  • Thanks for your input. I should not that the solution you provided only works in Java version 9. for people using java version 8 is will look like this instead. Map elements = new HashMap<>() {{ put("H", 1.008); }}; – Pierce Sutton May 14 '19 at 04:13
  • @PierceSutton Yes. That's why I included the link at the bottom. The link also explains the downsides of using that. Java isn't the most expressive language by nature. – Carcigenicate May 14 '19 at 04:57