因此,這是我第一次在這裏發佈。我試圖從文件讀取數據,從數據創建多個對象,然後將創建的對象放入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;
}