0

So this is my first time posting here. I am trying to read data from a file, create multiple objects from that data, and then place the created objects into an ArrayList. But every time I have tried, I just get multiple copies of the same object, instead of different objects. I am at my wits end.

Anyways, here is the code for the method to read the data in from the file. Thanks in advance for any help!

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

3 Answers 3

3

inside your while loop you should create a new instance of an object. Else it would only end up making modifications to the exisiting instance.

Correct way :

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

I cant see where you're creating the shopItem instance.

But if you're not creating a new ShopItem each time then every time you go around the loop you're just updating the one instance, and then adding it to the shopInventory.

Comments

1

You fill your ArrayList using the very same object. You should create a new instance of ShopItem:

while (shopData.hasNextLine()){
  ShopItem shopItem = new ShopItem();
  shopItem.setName(shopData.nextLine());
  ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.