gpt4 book ai didi

java - 在包含字符串和 double 的外部文本文件上使用扫描仪

转载 作者:行者123 更新时间:2023-12-01 09:20:27 26 4
gpt4 key购买 nike

编写一个 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

最佳答案

您的映射将字符串映射到字符串,而它应该将字符串映射到 double 。

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();

关于java - 在包含字符串和 double 的外部文本文件上使用扫描仪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40200960/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com