这似乎是一个订单列表。因此,与其将它们存储在不同的变量中,Order
不如通过使用类似
public class Order {
private String itemName;
private int quantity;
private double price;
public Order(String itemName, int quantity, double price) {
this.itemName = itemName;
this.quantity = quantity;
this.price = price;
}
// constructor overloading to help instantiate from Strings
public Order(String itemName, String quantity, String price) {
this (itemName, Integer.parseInt(quantity), Double.parseDouble(price));
}
// getters/setters
@Override
public String toString() { // to print Order values to console easily
return "{item = " + itemName +
", quantity = " + quantity +
", price = " + price + "}";
}
}
现在,只需在解析文件时填充对象实例Order
(认为一行 = 一个Order
对象),然后将它们添加到Collection
(订单)中。AList
似乎是一个不错的选择。
List<Order> listOfOrders = new ArrayList<Order>();
while(fileScanner.hasNextLine())
{
String line = fileScanner.nextLine();
String [] array = line.split(",");
for (int i = 0; i < array.length; i++)
{
// instantiate; initialize with passed params; add to list
listOfOrders.add(new Order(array[0], array[1], array[2]));
}
}
System.out.println(listOfOrders); // would use Order.toString()