-1

I'm trying to make a method where I can view the object. How can I access the bag1 object from the view() method?

public class ArrayBagUtilities {
    public void Create() {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Size of bag 1: ");
        int size = keyboard.nextInt();
        Bag bag1 = new ArrayBag(size);
        keyboard.nextLine();
        String itemStr;

        for (int i = 0; i < size; i++) {
            int n = i+1;
            System.out.print("Item " + n + ": ");
            itemStr = keyboard.nextLine();
            bag1.add(itemStr);
        }
    }

    public void view() {
        System.out.print(bag1);
    }
}
1
  • 1
    All you have to do is declare Bag bag1; outside of Create(): make it a class member, instead of a "local variable". public class ArrayBagUtilities { private Bag bag1; public void Create() {...} ...} Commented Feb 11, 2019 at 17:00

1 Answer 1

2

You can declare bag1 as attribute of your class.

public class ArrayBagUtilities {
    private Bag bag1;
    ....
    public void Create() {
    ....
        bag1 = new ArrayBag(size);
    ....
    }

    public void view() {
        System.out.print(bag1);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.