public static void nextGeneration(boolean[][] currentWorld, boolean[][] newWorld) {
boolean[][] world = null;
world = currentWorld;
int numLivingNeighbors = 0;
for (int i = 0; i < currentWorld.length; i++)
for (int j = 0; j < currentWorld[i].length; j++)
numLivingNeighbors =numNeighborsAlive(world, i, j);
boolean cellCurrentlyLiving = world[i][j];
isCellLivingInNextGeneration(numLivingNeighbors,currentWorld[i[j]);
我收到一条错误消息,说i和j无法解析为变量。 我尝试声明它们,但后来我得到一个错误,声明它们已被声明两次。
答案 0 :(得分:1)
您需要在for
循环中使用括号:
public static void nextGeneration(boolean[][] currentWorld, boolean[][] newWorld) {
boolean[][] world = null;
world = currentWorld;
int numLivingNeighbors = 0;
for (int i = 0; i < currentWorld.length; i++) {
for (int j = 0; j < currentWorld[i].length; j++) {
numLivingNeighbors =numNeighborsAlive(world, i, j);
boolean cellCurrentlyLiving = world[i][j];
isCellLivingInNextGeneration(numLivingNeighbors,currentWorld[i[j]);
}
}
// might there be other code you did not show us?
return;
}
当你使用for
循环而没有括号时,它只会将直线或后续行视为循环的一部分。因此,您的原始代码实际上与此相同:
for (int i = 0; i < currentWorld.length; i++) {
for (int j = 0; j < currentWorld[i].length; j++) {
numLivingNeighbors =numNeighborsAlive(world, i, j);
}
}
boolean cellCurrentlyLiving = world[i][j];
isCellLivingInNextGeneration(numLivingNeighbors,currentWorld[i[j]);
换句话说,您引用了实际循环的loop
变量i
和j
。