Hi all, could anyone tell me how to read a unorder file into order output, I wrote a method that only read order file(begin with product). The following is my code.
My input file like this:
product Apples
location 10 Downing Street
London
England
quantity 382764
location Akihabara
Tokyo
Japan (East)
product Transistor Radios
quantity 10000 cases
location Woolies Supermarket
product Weetbix flakes
Marrackville
Sydney NSW Australia
Thanks in advance.
public static ArrayList getData(String fileName) {
ArrayList<Product> recordList = new ArrayList<Product>();
int index = -1;
try {
File file = new File(fileName);
Scanner reader = new Scanner(file);
String s;
Product p = null;
boolean locationActive = false;
while (reader.hasNext()) {
s = reader.nextLine();
Scanner line = new Scanner(s);
String cmd;
if (line.hasNext()) {
cmd = line.next();
if (cmd.equalsIgnoreCase("product")) {
index++;
p = new Product();
p.setName(line.nextLine());
recordList.add(index, p);
locationActive = false;
} else if (cmd.equalsIgnoreCase("location")) {
p.setLocation(line.nextLine());
recordList.set(index, p);
locationActive = true;
} else if (cmd.equalsIgnoreCase("quantity")) {
if (line.hasNextInt()) {
p.setQuantity(line.nextInt());
recordList.set(index, p);
}
locationActive = false;
} else if (locationActive) {
String location = p.getLocation() + " " + s;
p.setLocation(location);
recordList.set(index, p);
} else
System.out.println("Error: no command:" + s);
}
}
reader.close();
return recordList;
} catch (Exception e) {
System.out.println("Error:- " + e.getMessage());
return null;
}
}