gpt4 book ai didi

java - 将循环编号添加到对象的名称

转载 作者:行者123 更新时间:2023-11-29 09:03:44 25 4
gpt4 key购买 nike

我在 Java 中有这段代码

for (int j = 0; j < 8; j++) 
{
Boton[1][j].setIcon(PeonN);
Peon PeonNegro = new Peon('N');
Boton[6][j].setIcon(PeonB);
}

这是国际象棋的,我希望每个新对象都有循环的数量,在不创建数组的情况下独立使用它,有类似的东西

for (int j = 0; j < 8; j++) 
{
Boton[1][j].setIcon(PeonN);
Peon PeonNegro+i = new Peon('N');
Boton[6][j].setIcon(PeonB);
}

所以我会有 PeonNegro0、PeonNegro1 等等...

最佳答案

如果没有数组或Collection,您将无法执行此操作。 (在 Java 中,很难使用动态变量名)。您必须在 for 循环之外声明类似数组或 ArrayList 的内容,如下所示。

Peon[] peons = new Peon[8];
for (int j = 0; j < 8; j++)
{
Boton[1][j].setIcon(PeonN);
peons[j] = new Peon('N');
Boton[6][j].setIcon(PeonB);
}

// So we can access a single peon like this
Peon p3 = peons[3];

// Or iterate over all peons and get the cycle number like this
for (int cycle_num = 0; cycle_num < 8; cycle_num++) {
Peon peon = peons[cycle_num];

// Do something with peon and cycle_num here

}

关于java - 将循环编号添加到对象的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16072961/

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