I have this code in Java
for (int j = 0; j < 8; j++)
{
Boton[1][j].setIcon(PeonN);
Peon PeonNegro = new Peon('N');
Boton[6][j].setIcon(PeonB);
}
This is for a Chess, I want each new object to have the number of the loop do use it independently without creating an array, to have something like
for (int j = 0; j < 8; j++)
{
Boton[1][j].setIcon(PeonN);
Peon PeonNegro+i = new Peon('N');
Boton[6][j].setIcon(PeonB);
}
So I'll have PeonNegro0, PeonNegro1 and so on...
You aren't going to be able to do this without an array or Collection
. (In Java, it would be quite difficult to use a dynamic variable name). You'll have to declare something like an array or ArrayList
outside of your for loop, as shown below.
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
}