我有一个带球的课程。
在另一个名为CollectionBalls的类中,我有一组Balls(多么令人惊讶)
类CollectionBalls有一个类型为ball的ArrayList:
ArrayList <Balls> myBalls;
我想要做的是当我创建对象时,CollectionBalls是:在构造函数的参数中设置球的ammount。
像
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);
}
}
但我不能用i动态地创造一个新球。
如何根据参数创建对象数量?
编辑:我可以用testBall重命名我,但是testBall是一个对象,而不是10个对象,如球1球2球3对吗?
答案 0 :(得分:2)
我看到两个问题
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);
}
}
答案 1 :(得分:2)
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());
}
}