我正在编写一个程序,该程序查找单个字符串中多个值的和。例如,您放入H2O,它将返回该化学物质的摩尔质量值(2 * H + O)。因此,我复制了元素周期表并列出了值,例如“ private double H = 1.008;”。所以问题是我需要根据变量的名称获取该值。这是一个例子。
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')
答案 0 :(得分:1)
请勿为此使用原始变量。请改用Map
:
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;
}
或者,稍微整洁:
Map<String, Double> elemWeights = Map.ofEntries(
entry("H", 1.008),
entry("Li", 6.94)
...
);
或者请参见here,以了解其他基于您使用的Java版本来编写它的方式。