I'm reading from a pretty simple file that displays items and how much they cost. It looks like this:
Shoes 10.00
Jersey 20.00
Cookies 15.00
Light Bulbs 2.00
Paper 5.00
I want to map every item to how much it costs and my current code works just fine. However, it looks a bit clunky and initializes variables with null that my project's submission server doesn't like and treats as a bug. I'm looking for a way to translate this into something a lot more elegant and thus learn to read files another way apart from relying on the Scanner class. Maybe using BufferedReader or PrintReader or something of the ilk that I have never really grasped. Help appreciated.
private TreeMap<String, Double> prices = new TreeMap<String, Double>();
public void readFromFile(String fileName){
File file = new File(fileName);
Scanner sc = null; //Server treats this as a bug.
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc.hasNextLine()) {
Scanner sc2 = new Scanner(sc.nextLine());
while (sc2.hasNext()) {
String s = sc2.next(); //Gets the item name
prices.put(s, Double.parseDouble(sc2.next())); //The next word is the price
}
sc2.close();
}
}