我正在尝试使用散列图编写Java单元转换程序。每次我尝试运行我的代码时,convert()
都会抛出异常,我不知道为什么会这样做?这里发生了什么?请给出提示,而不是完整的答案。谢谢!
FWIW,输入遵循格式3 meters to inches
。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Conversions {
static private ArrayList<Map<String, Double>> conversions = new ArrayList<Map<String, Double>>();
Map<String, Double> conversion;
{ // length
conversion = new HashMap<String, Double>();
conversion.put("kilometers", 1e-3);
conversion.put("meters", 1.0);
conversion.put("angstroms", 1e-10);
conversion.put("inches", 39.3701);
conversion.put("yards", 1.09361);
conversion.put("attoparsecs", 32.4077929);
conversion.put("miles", 0.000621371);
conversions.add(conversion);
}
{ // weight
conversion = new HashMap<String, Double>();
conversion.put("kilograms", 1.0);
conversion.put("grams", 1000.0);
conversion.put("pounds", 2.20462);
conversion.put("ounces", 35.274);
conversion.put("slugs", 0.0685217649);
conversion.put("hogsheads of Beryllium", 440.7);
conversions.add(conversion);
}
public static double convert(double value, String unitFrom, String unitTo) throws Exception {
for (int i = 0; i < conversions.size(); i++) {
if (conversions.get(i).containsKey(unitFrom) && conversions.get(i).containsKey(unitTo)) {
return value * conversions.get(i).get(unitTo) / conversions.get(i).get(unitFrom);
}
}
throw new Exception(value + " " + unitFrom + " can't be converted to " + unitTo);
}
private static void parse(String line) {
String[] splitStrings = line.split("\\s+");
double value = Double.parseDouble(splitStrings[0]);
try {
double convertedValue = convert(value, splitStrings[1], splitStrings[3]);
System.out.format("%f %s is %f %s%n", value, splitStrings[1], convertedValue, splitStrings[3]);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
parse(scanner.nextLine());
scanner.close();
}
}
答案 0 :(得分:1)
提示:如果我是你,我会在方法转换循环中放入一个断点,并检查这种情况是否适用:
if (conversions.get(i).containsKey(unitFrom) && conversions.get(i).containsKey(unitTo)) {