2015-03-24 74 views
0
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循環之外打印庫存數組,但每次我這樣做時,庫存數組中的所有元素都將被item1的最後一項替換。如何將項目存儲到while循環外的數組中?

如果我留在while循環內,一切正常。

+0

我想我們需要看到'grocery.readItem(fileInput);' – 2015-03-24 23:11:32

+0

代碼的部分代碼只是讀取一個字符串的代碼,那麼該字符串應該存儲在庫存數組中,但它會一直越過由庫存中的最後一項寫成。 – 2015-03-24 23:17:47

+1

我不知道發生了什麼,但是您需要爲我們提供足夠的代碼來重現問題,否則無法提供幫助。我可能是錯的,但我不認爲這個錯誤出現在我們可以看到的代碼中。 – 2015-03-24 23:19:33

回答

0

我還不能發表評論,所以我會在這裏回答。

在我opnion,根據你說,如果你調用,而外面的片段:

item1.printInventory(inventory,counter); 

這會不會僅打印最後一個元素? 因爲您正在使用處於最後位置的計數器和庫存數組。

打印,而以外的所有庫存,您需要一種方法:

item1.printInventory(inventory); 


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

這就是你想要什麼?