Reputation: 12331
I have a Class with Balls.
In another class called CollectionBalls i have a collection of Balls (what a suprise)
The class CollectionBalls has a ArrayList of the type balls :
ArrayList <Balls> myBalls;
What i want to do is when i create the object CollectionBalls is : set the ammount of balls in the parameter of the constructor.
like
public CollectionBalls(int amountOfBalls)
{
myBalls = new ArrayList <Balls>();
setAmountOfBalls(amountOfBalls);
}
public void setAmountOfBalls(int amountOBalls)
{
for (int i = 0; i < amountOBalls; i ++)
{
// Create a new ball
Ball i = new Ball();
// Add the ball to the collection of ball
myBalls.add(i);
}
}
but i cant create a new ball dynamicly with i.
How can i create the amount of object based on the parameter?
edit: i can rename i with something like testBall but testBall is one object then instead of 10 object like ball 1 ball 2 ball 3 right?
Upvotes: 1
Views: 136
Reputation: 1265
public CollectionBalls(int amountOfBalls)
{
myBalls = new ArrayList <Balls>();
setAmountOfBalls(amountOfBalls);
}
public void setAmountOfBalls(int amountOBalls)
{
for (int i = 0; i < amountOf**Registers**; i ++)
// Add the ball to the collection of ball
myBalls.add(new Balls());
}
}
Upvotes: 2
Reputation: 201527
I see two issues
public void setAmountOfBalls(int amountOBalls)
{
for (int i = 0; i < amountOBalls; i++)
{
// Create a new ball
// Ball i = new Ball(); // you have a plural class name, but were trying to
// make it singular here and you already have an
// integer variable called i.
Balls ball = new Balls();
// Add the ball to the collection of ball
myBalls.add(ball);
}
}
Upvotes: 2