【问题标题】:Two of my variables cannot be resolved to a variable我的两个变量无法解析为一个变量
【发布时间】:2016-01-22 14:01:45
【问题描述】:
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 无法解析为变量。 我尝试声明它们,但后来我收到一个错误,指出它们已被声明了两次。

【问题讨论】:

  • 最后一行的 i 后面应该有一个右方括号。 - 当前世界[i][j]
  • 更重要的是,您希望在嵌套循环声明的末尾有一个左大括号 - 让您的 IDE 格式化您的代码,然后您会看到发生了什么...

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


【解决方案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

【讨论】:

    猜你喜欢
    • 2014-06-17
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 2011-11-27
    • 1970-01-01
    • 2012-04-14
    • 1970-01-01
    相关资源
    最近更新 更多