Liam.C Liam.C - 1 month ago 8
Java Question

Reading values from a text file and separating into String and double

I am having this error with my code:
Exception in thread "main" java.util.InputMismatchException

I know the reason for the error, the entire line is being converted into a String, but I am unsure how of how to fix it. I have tried reading up on Delimiters **Exception in thread "main" java.util.InputMismatchException** How do I use a delimiter in Java Scanner?

but it all sounds too complex for my level of understanding.

My code:

import java.util.*;
import java.io.*;
public class POSmain{
public static void main(String[] args)throws Exception {


other code

//create 3 collections to store input, with scanners to extract input
Map<String, Double> products = new TreeMap<String, Double>();
Scanner stock = new Scanner(new File("prices.txt"));


my failed attempt at using a Delimiter

//Delimiter to remove whitespace
stock.useDelimiter("\\s*[a-z]\\s");


more code

//populate each collection with while loops
while(stock.hasNext()){
tempString = stock.nextLine();
tempdouble = stock.nextDouble();
products.put(tempString,tempdouble);

}
stock.close();


Trying to read this file:

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


I am not to change nor delete white spaces from the file.
I would be most grateful for any help or advice on how I should extract the values. I am happy to provide more code upon request but it I expect this is all that is required.
Thanks again and I appreciate any help I get.

Answer

From the looks of your file, your delimeter is either some combination of tabs and spaces (the separating characters between the item name and number), or the newline at the end of each line.

In this case, your delimeter should be \\s+, meaning one or more whitespace characters. So your code should look something like this:

Map<String, Double> products = new TreeMap<String, Double>();
Scanner stock = new Scanner(new File("prices.txt")); 
stock.useDelimiter("\\s+");

while (stock.hasNext()) {
    tempString = stock.nextLine();
    tempdouble = stock.nextDouble();
    products.put(tempString,tempdouble);
}
stock.close();

I tested your input file with code similar to what is above on IntelliJ, and it appears to be working.