java如何将项目存储到while循环之外的数组中?
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
循环中,一切正常
# 1 楼答案
我还不能发表评论,所以我会在这里回答
在我的观点中,根据你写的片段,如果你在时间之外打电话:
这不会只打印最后一个元素吗? 因为您使用的是最后一个位置的计数器和库存数组
要打印while之外的所有库存,需要一种方法:
这就是你想要的