2014-02-23 107 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()); 
    ... 
} 
相關問題