Cou*_*n22 0 java arrays for-loop
我正在努力改变一些代码的长度.
我有这个:
rects[1].setLocation(0, 0);
rects[2].setLocation(100, 0);
rects[3].setLocation(200, 0);
rects[4].setLocation(300, 0);
rects[5].setLocation(400, 0);
rects[6].setLocation(500, 0);
rects[7].setLocation(0, 50);
rects[8].setLocation(100, 50);
rects[9].setLocation(200, 50);
rects[10].setLocation(300, 50);
rects[11].setLocation(400, 50);
rects[12].setLocation(500, 50);
rects[13].setLocation(0, 100);
rects[14].setLocation(100, 100);
rects[15].setLocation(200, 100);
rects[16].setLocation(300, 100);
rects[17].setLocation(400, 100);
rects[18].setLocation(500, 100);
rects[19].setLocation(0, 150);
rects[20].setLocation(100, 150);
rects[21].setLocation(200, 150);
rects[22].setLocation(300, 150);
rects[23].setLocation(400, 150);
rects[24].setLocation(500, 150);
Run Code Online (Sandbox Code Playgroud)
我把它改成了这个:
for(int i = 1; i < 25; i++)
{
for(int j = 0; j < 550; j +=50)
{
for(int k = 0; k < 550; k +=50)
{
rects[i].setLocation(j, k);
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是后者不起作用,尽管它应该.我的问题是,问题是什么?我已经尝试了很多方法解决问题,但没有任何作用.我不得不谷歌这个问题,因为我不知道问题是什么.如果值得注意的话,这也是来自applet的代码.
你的循环应该如下所示:
for (int i=0; i<24; i++) {
int x = (i%6)*100;
int y = (i/6)*50;
//Array indexes start from 1, whereas this
//loop starts from 0, hence adjusting below
rects[i+1].setLocation(x, y);
}
Run Code Online (Sandbox Code Playgroud)
您不需要三个嵌套循环,因为您只分配给一个数组.
顺便说一句,你的数组索引不应该rects从0开始吗?
| 归档时间: |
|
| 查看次数: |
126 次 |
| 最近记录: |