gpt4 book ai didi

java - 带数组的 For 语句

转载 作者:行者123 更新时间:2023-12-01 06:33:06 26 4
gpt4 key购买 nike

我正在研究一种更改某些代码长度的方法。

我有这个:

    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);
}
}
}

问题是后者不起作用,尽管它应该起作用。我的问题是,问题出在哪里?我尝试了很多方法来解决这个问题,但没有任何效果。我必须用谷歌搜索这个问题,因为我不知道问题是什么。如果值得注意的话,这也是来自小程序的代码。

最佳答案

你的循环应该是这样的:

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);
}

您不需要三个嵌套循环,因为您只分配给一个数组。

顺便说一句,矩形 的数组索引不应该从 0 开始吗​​?

关于java - 带数组的 For 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12118873/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com