我的两个变量无法解析为变量

时间:2015-10-23 05:32:52

标签: java variables for-loop int conways-game-of-life

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无法解析为变量。 我尝试声明它们,但后来我得到一个错误,声明它们已被声明两次。

1 个答案:

答案 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变量ij