在我的构造函数中,我将气泡数组设置为参数中输入的大小。例如,如果用户输入" 9"对于" numberOfBubbles",然后创建一个包含9个气泡对象的数组。
private double canvasWidth;
private double canvasHeight;
private Bubble[] bubbles;
int count;
public Mover(double width, double height, int numberOfBubbles) {
canvasWidth = width;
canvasHeight = height;
bubbles = new Bubble[numberOfBubbles];
for (int i = 0; i < numberOfBubbles; i ++){
bubbles[i] = new Bubble();
bubbles[i].showBubble(width, height);
}
count = 1000;
}
public void moveAllAndBounce() {
for( int p = 0; p < count; p++ ){
bubbles[].moveIt();
}
}
在我的名为&#34; moveAllAndBounce&#34;的方法中,我想在for循环中围绕屏幕移动这9个气泡对象,这将在P = 1000时结束,但是我不知道要在括号中输入什么[]使这个工作,因为数组的大小是在构造函数的参数中启动的。如果我写&#34;起泡[p]&#34;这是行不通的,因为如果我想在构造函数中将数组的大小设置为9,那么循环将在p = 9时停止。我在括号中写什么才能使其工作?
答案 0 :(得分:2)
您的气泡已编号。第一个循环清楚地表明该编号介于0和numberOfBubbles-1之间;
0, 1, 2, ..., numberOfBubbles-3, numberOfBubbles-2, numberOfBubbles-1
所以,如果你想在第5个泡泡上调用moveIt()
,那就是索引4,你会写
bubbles[4].moveIt();
如果您需要移动所有气泡,我建议您分别在每个气泡上使用moveIt()
循环。
答案 1 :(得分:2)
我建议使用内部转换为常规for-each-loop
的{{1}},编译器负责检查数组或集合的大小(实现Iterable)。
for-loop
答案 2 :(得分:1)
如果你想将每个气泡移动1000次,你可以写出类似的东西:
public void moveAllAndBounce() {
for( int p = 0; p < count; p++ ){
for(int i=0; i<numberOfBubbles; i++){
bubbles[i].moveIt();
}
}
}
如果你想要完全1000个moveIt()函数调用,那么首先你需要将count改为count / numberOfBubbles
答案 3 :(得分:1)
所有数组都有一个名为length
的变量,arr.length
可以访问它。
在你的情况下,你必须建立两个循环:一个用于泡泡,一个用于移动。
应该是这样的:
public void moveAllAndBounce(){
for (int i = 0; i < bubbles.length; i ++)
for(int p = 0; p < count; p ++)
bubbles[i].moveIt();
}