0

I have a method that creates object and store it into arrayList. I am running the method in "console menu", so if I run the addObject method 3 times and print the arrayList I want to have 3 objects as content of the arrayList. I want the arrayList index to keep increasing as long I the meun runs. list.add(bk) deletes existing object and create new one. How do I correct the below code to make the method insert new object and not deleting existing one.

code

public static void addObject() {
        String name, note;
        double price;

        Scanner input = new Scanner(System.in);

        System.out.println("Enter name: ");
        name = input.next();
        System.out.println("Enter note: ");
        note = input.next();
        System.out.println("Enter price: ");
        price = input.nextDouble();


        storeItem bk = new storeItem(name, note, price);

        //how do I complete this part?
        ArrayList<storeItem> list = new ArrayList<>();
        list.add(bk); //detetes existing and add current. I want to keep existing and add new

        for (int index = 0; index < list.size(); index++) {
            System.out.println("Object: "+ index + "\n" + list.get(index));
        }
    }

1 Answer 1

4

Move the declaration (and initialization) of your List from with-in the method to outside of the method. And prefer the List interface to the concrete ArrayList type. For example,

private static List<storeItem> list = new ArrayList<>();

Finally, by Java naming conventions, the class storeItem should be named StoreItem.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the response. Please how do I then call the "list" within the addObject method?
list.add(bk); (after removing the current declaration).

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.