2014-02-23 44 views
0

因此,这是我第一次在这里发布。我试图从文件读取数据,从数据创建多个对象,然后将创建的对象放入ArrayList中。但每次尝试时,我都会得到同一个对象的多个副本,而不是不同的对象。我不知道该怎么做。从Java中的文件中读取数据到数组列表中的问题

无论如何,这里是从文件中读取数据的方法的代码。预先感谢任何帮助!

public void openShop() throws IOException{ 
    System.out.println("What is the name of the shop?"); 
    shopName = keyboard.nextLine(); 
    setShopFile(); 
    File openShop = new File(shopFile); 
    if (openShop.isFile()){ 
     Scanner shopData = new Scanner(openShop); 
      shopName = shopData.nextLine(); 
      shopOwner = shopData.nextLine(); 

      while (shopData.hasNextLine()){ 
       shopItem.setName(shopData.nextLine()); 
       shopItem.setPrice(Double.parseDouble(shopData.nextLine())); 
       shopItem.setVintage(Boolean.parseBoolean(shopData.nextLine())); 
       shopItem.setNumberAvailable(Integer.parseInt(shopData.nextLine())); 
       shopItem.setSellerName(shopData.nextLine()); 
       shopInventory.add(shopItem); 

      } 
      setNumberOfItems(); 
    } 
    else 
     System.out.println("That shop does not exist. Please try to open" + 
          "the shop again."); 
    isSaved = true; 
} 

回答

1

我不知道你在哪里创建shopItem实例。

但是,如果您不是每次创建新的ShopItem,那么每当您绕过循环时,您只需更新一个实例,然后将其添加到shopInventory中。

3

在你的while循环中,你应该创建一个对象的新实例。否则它只会最终对现有实例进行修改。

正确方法:

while (shopData.hasNextLine()){ 
    shopItem = new ShopItem(); //This will create a new Object of type ShopItem 
    shopItem.setName(shopData.nextLine()); 
    shopItem.setPrice(Double.parseDouble(shopData.nextLine())); 
    shopItem.setVintage(Boolean.parseBoolean(shopData.nextLine())); 
    shopItem.setNumberAvailable(Integer.parseInt(shopData.nextLine())); 
    shopItem.setSellerName(shopData.nextLine()); 
    shopInventory.add(shopItem); 
} 
1

您使用相同的对象填写您的ArrayList。您应该创建ShopItem的新实例:

while (shopData.hasNextLine()){ 
    ShopItem shopItem = new ShopItem(); 
    shopItem.setName(shopData.nextLine()); 
    ... 
} 
相关问题