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
循環內,一切正常。
我想我們需要看到'grocery.readItem(fileInput);' – 2015-03-24 23:11:32
代碼的部分代碼只是讀取一個字符串的代碼,那麼該字符串應該存儲在庫存數組中,但它會一直越過由庫存中的最後一項寫成。 – 2015-03-24 23:17:47
我不知道發生了什麼,但是您需要爲我們提供足夠的代碼來重現問題,否則無法提供幫助。我可能是錯的,但我不認爲這個錯誤出現在我們可以看到的代碼中。 – 2015-03-24 23:19:33