为什么我的构造函数没有正确初始化变量?

时间:2018-03-07 03:13:45

标签: java arraylist compiler-errors

所以我试图读取一个文件并创建这些对象的集合。文件中的对象数量是我想要将numItems变量设置为的,但是我收到了错误。

public class Warehouse
{
// instance variables (fields)  
private final static int MAX = 60;
private ArrayList <Item> stock;
private int numItems;

// the constructor
public Warehouse()
{
    stock = new ArrayList<Item>();
    numItems = loadData();
}


public int loadData(File infile) throws IOException
{
    Scanner in = new Scanner (infile);
    int number = 0;

    while(in.hasNext())
    {
        String item = in.nextLine();
        String [] items = item.split(" ");
        String itemNum = items[0];
        String itemName = items[1];
        int onHand = Integer.parseInt(items[2]);
        int committed = Integer.parseInt(items[3]);
        int onOrder = Integer.parseInt(items[4]);
        double price = Double.parseDouble(items[5]);
        int reOrderPt = Integer.parseInt(items[6]);
        int econOrder = Integer.parseInt(items[7]);
        stock.add(number, new Item(itemNum, itemName, onHand, committed, onOrder, price, reOrderPt, econOrder));
        number++;
    }

    return number;
}  

这是我主要阅读文件并将其传递给loadData方法的地方:

public static void main(String args[]) throws IOException
{
    // complete the main by adding the necessary variables and statements
    int choice;

    Scanner kb = new Scanner(System.in);
    Warehouse inStock = new Warehouse();
    String number = "";
    int amount = 0;

    File infile = new File("inventory.txt");
    inStock.loadData(infile);

1 个答案:

答案 0 :(得分:1)

  1. 您收到错误是因为loadData()需要File参数,而您却没有通过任何错误。
  2. 当您拨打ArrayList.size()时,为什么需要跟踪项目数?