如何将项目存储到while循环外的数组中?

时间:2015-03-24 23:05:37

标签: java loops while-loop

Scanner fileInput;  // inventory file
int counter=0;
File inFile = new File("inventory.dat");
try 
{
    fileInput = new Scanner(inFile);// open inventory file and read

    while (fileInput.hasNext())
    {

        GroceryItem grocery= new GroceryItem();
        grocery.readItem(fileInput);
        //System.out.println(item1);
        inventory[counter]=grocery;


        //item1.printInventory(inventory,counter);
        total=counter;
        counter++;

    }

}

catch(FileNotFoundException e)
{
    System.out.println("Error: inventory.dat not found"); 

}

我正在尝试在try....catch块中的while循环之外打印库存数组,但每次执行此操作时,库存数组中的所有元素都将替换为{{1的最后一项}}

如果我留在item1循环中,一切正常。

1 个答案:

答案 0 :(得分:0)

我还不能发表评论,所以我会在这里回答。

在我的观察中,根据您放置的片段,如果您在外面打电话:

item1.printInventory(inventory,counter);

这不会只打印最后一个元素吗? 因为您使用的是最后位置的计数器和库存数组。

要打印while之外的所有库存,您需要一个方法:

item1.printInventory(inventory);


//The Method in the class of item1
private void printInventory(GroceryItem[] inventory) {
    for (GroceryItem item: inventory) {
        System.out.println(item);
    }
}

那是你想要的?