0

Hi I'm very new to Java and have this HW problem, we are asked to build a Class RandomBag -- a generic bag container which allows 'RandomPick' of an element. I keep getting this error I have little idea to fix, any help is greatly appreciated!

  public RandomBag() {
      ArrayList<E> Bag=new ArrayList<E>();
      Random Rand =new Random();
  }
  public RandomBag(int seed) { 
      ArrayList<E> Bag=new ArrayList<E>();
      Random Rand =new Random(seed);
Robert
  • 133
  • 1
  • 3
  • 10

5 Answers5

1

You are never initializing the variables rand or bag, so they are always null. In your constructors you need to use rand and bag, not Rand or Bag. For example:

public RandomBag() {
    bag = new ArrayList<E>();
    rand = new Random();
}
Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
1

A few things, in your constructors change

ArrayList<E> Bag=new ArrayList<E>();
Random Rand =new Random();

to

bag=new ArrayList<E>();
rand = new Random(seed);

few things to remember: variables are case sensitive. if you add a type, you are defining, not setting, ie:

ArrayList<E> bag=new ArrayList<E>();

is defining a new variable bag while

bag=new ArrayList<E>();

sets the existing variable bag to new ArrayList<E>();

Epicblood
  • 1,167
  • 2
  • 10
  • 29
0

You are trying to initialise new variable in constructor. Assign it to variables that you have declared instead.

  public RandomBag(int seed) { 
  bag=new ArrayList<E>();
  rand =new Random(seed);

}

Sunil Rajashekar
  • 350
  • 2
  • 18
0

Change your constructors:

 public RandomBag() {
      bag = new ArrayList<E>();
      rand = new Random();
  }
  public RandomBag(int seed) { 
      bag = new ArrayList<E>();
      rand = new Random(seed);
  }

The output is:

10 10 11 12 13 14 15 16 17 Random pick: 15 Random pick: 16 Random pick: 13 10 10 11 12 14 17**

Jemuel Elimanco
  • 416
  • 2
  • 4
  • 20
-1

In your constructors... Replace

ArrayList<E> Bag=new ArrayList<E>();
  Random Rand =new Random(seed);

with

Bag=new ArrayList<E>();
   Rand =new Random(seed);
Daniel Stancu
  • 52
  • 2
  • 8
  • cannot find symbol Bag. cannot find symbol Rand – Baby Apr 22 '15 at 02:13
  • bag, not Bag, sorry, and rand, not Rand. – Daniel Stancu Apr 22 '15 at 02:14
  • The idea is that you declare this instance variables in your class, but you do not initialize them in your constructors, but you declare other 2 local (to the constructors) variables and initialize them there, which has nothing to do with your instance variables (bag and random). – Daniel Stancu Apr 22 '15 at 02:17
  • you can edit your post, not posting as a comment. – Baby Apr 22 '15 at 02:18