[英]For statement with arrays
我正在研究一种更改某些代码长度的方法。
我有这个:
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);
我将其更改为:
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);
}
}
}
问题是后者不起作用,尽管应该起作用。 我的问题是,怎么了? 我已经尝试了多种解决问题的方法,但是没有任何效果。 我必须通过Google搜索这个问题,因为我不知道问题出在哪里。 如果值得注意的话,这也是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);
}
您只需要分配给一个数组,就不需要三个嵌套循环。
顺便说一下,您的rects
数组索引不应该从0开始吗?
您正在执行最里面的语句24 * 10 * 10 = 2400次。
您应该将其编写为单个循环,并按顺序计算x和y值。
如果您稍微浏览一下代码,就会发现您的代码执行以下操作:
rects[1].setLocation(0, 0);
rects[1].setLocation(0, 50);
rects[1].setLocation(0, 100);
rects[1].setLocation(0, 150);
...
这显然不是您想要的。 您只需要设置24个值,因此只需一个循环。 您可以使用取模运算符来获取适当的值。
for(int i = 1; i < 25; i++)
{
rects[i].setLocation(((i-1)%6)*100, ((i-1)/6)*50);
}
一些解释:
(i-1)/6
起作用的原因是这是整数除法。 结果将被截断为整数。 例如,11/6 11/6 = 1
。
我想你想要这样的东西:
/**
* Do two things every 6th iteration:
*
* 1.) Reset j to zero
* 2.) Increment k by 50
*
* Otherwise increment j by 100 every iteration.
*
*/
for (int i = 1; i < 25; i ++) {
if (isMultipleOfSix(i)) {
j = 0;
k += 50;
}
rects[i].setLocation(j, k);
j += 100;
}
private boolean isMultipleOfSix(int num) {
return ( num % 6 == 0 );
}
您正在遍历i
每个值的所有j
和k
,最终将所有位置都设置为(500,500)。
您应该做的是将j
和k
保持为循环外部的单独变量(也许将它们称为x
, y
),并在每个循环中对其进行更新,例如
int x = 0;
int y = 0;
for(int i=0; i<25; i++) {
rects[i].setLocation(x, y);
if(x == 500) {
x = 0;
y += 50;
} else {
x += 100;
}
}
尝试类似这样的事情:
for (int i = 0, y = 0; i <= 24; y += 50) {
for (int x = 0; x <= 500; x += 100) {
locs[++i].setLocation(x, y);
}
}
而且,不,我不是一个优化的编译器。
我在您的代码中看到了一些可能会给您带来问题的问题:
这是我会做的:
for(int i = 1, j = 0, k = 0; i < 24; j += 100)
{
if(j > 500)
{
j = 0;
}
if(i%6 == 0)
{
k += 50;
}
rects[i].setLocation(j, k);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.