使一个Java程序读取包含字符串和双精度值的文本文件作为价目表,并将它们存储在Hashmap中。在nextDouble()行中继续获取“ java.util.InputMismatchException”错误。
码:
public static void main(String[] args) throws IOException {
String priceList = "src/" + args[0];
String cartOne = "src/" + args[1];
String cartTwo = "src/" + args[2];
Scanner priceScan = new Scanner(new File(priceList));
priceScan.useDelimiter(" ");
HashMap<String, Double> prices = new HashMap<String, Double>();
priceScan.useDelimiter(" ");
while (priceScan.hasNext()) {
String name = priceScan.next();
Double price = priceScan.nextDouble();
prices.put(name, price);
}
priceScan.close();
System.out.println(prices);
}
文本文件如下:
TV 999.99
Table 199
Bed 499.99
Chair 45.49
Milk 3.00
Butter 2.84
Tomato 0.76
Onion 0.54
Lettuce 1.00
Ham 2.50
Bread 1.75
最佳答案
您的映射是将字符串映射为字符串,而应将字符串映射为双精度。
Scanner priceScan = new Scanner(new File(priceList));
HashMap<String, Double> prices = new HashMap<String, Double>();
while (priceScan.hasNext()) {
String name = priceScan.next();
Double price = priceScan.nextDouble();
prices.put(name, price);
}
priceScan.close();