有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

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

    在我的观点中,根据你写的片段,如果你在时间之外打电话:

    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);
        }
    }
    

    这就是你想要的