Brandon Liuslie Brandon Liuslie - 1 month ago 6
Java Question

Using scanner on an external text file containing string and doubles

Making a java program to read a text file containing both string and doubles as a price list and storing them in a Hashmap. Keep on getting "java.util.InputMismatchException" errors in the nextDouble() line.
Code:

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


the text file is as follows:

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

Answer

Just use an appropriate delimeter with your scanner, appropriate meaning whitespace and newlines. Also, as others have already mentioned your map was using the wrong mapping. It should be mapping strings to doubles.

Scanner priceScan = new Scanner(new File(priceList));
priceScan.useDelimiter("\\s+|\\r\\n");   // use \\s+|\\n on Linux
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();