So for part of my assignment I have to pull information from a file outside of Java. I have already gotten that part done. The problem is that I am not sure how to actually put the strings from the files into a variable or loop that will work for the next part. In the following code I need to replace the part of the code that have that says Item = Tomato... with singular lines from the outfile. I am not sure how to do this. My major concern would be making sure it was not hardcoded for each line, I am guessing it will involve looping through each line in some way or form. Any help would be great.
How I originally added the items in hardcoded, as opposed to what I want to do which is input them from an outfile:
list.add(new Item("Ketchup", 1.00, 10, 2.00, itemType.FOOD));
list.add(new Item("Mayo", 2.00, 20, 3.0, itemType.FOOD));
list.add(new Item("Bleach", 3.00, 30, 4.00, itemType.CLEANING));
list.add(new Item("Lysol", 4.00, 40, 5.00, itemType.CLEANING));
Code
Scanner s = new Scanner(new File("inventory.out"));
ArrayList<String> inventoryList = new ArrayList<String>();
while (s.hasNext()){
inventoryList.add(s.next());
}
s.close();
System.out.println(inventoryList);
String item = "Tomato,30,1.25,6.50";// input String like the one you would read from a file
String delims = "[,]"; //delimiter - a comma is used to separate your tokens (name, qty,cost, price)
String[] tokens = item.split(delims); // split it into tokens and place in a 2D array.
for (int i=0; i < 4; i++) {
System.out.println(tokens[i]); // print the tokens.
}
String name = tokens[0]; System.out.println(name);
int qty = Integer.parseInt(tokens[1]);System.out.println(qty);
double cost = Double.parseDouble(tokens[2]);System.out.println(cost);
Console output right now:
[Ketchup,1.00,10,2.00,itemType.FOOD, Mayo,2.00,20,3.00,itemType.FOOD, Bleach,3.00,30,4.00,itemType.CLEANING, Lysol,4.00,40,5.00,itemType.CLEANING]
Contents of the outfile:
Ketchup,1.00,10,2.00,itemType.FOOD
Mayo,2.00,20,3.00,itemType.FOOD
Bleach,3.00,30,4.00,itemType.CLEANING
Lysol,4.00,40,5.00,itemType.CLEANING