【问题标题】:private final int blanki; private final int blankj;私人最终诠释空白;私人最终 int 空白j;
【发布时间】:2015-05-22 17:19:59
【问题描述】:

我有这个代码:

public final class Board {

    private final int[][] blocks;
    private final int N;
    private final int blanki;
    private final int blankj;
    int i, j;

    // construct a board from an N-by-N array of blocks
   public Board(int[][] blocks)  {

        this.blocks = new int[blocks.length][blocks.length];

        for(i = 0; i < blocks.length; i++){
            for(j = 0; j < blocks.length; j++){
                this.blocks[i][j] = blocks[i][j];
                if(blocks[i][j] == 0) {
                    int f = i;
                    int c = j;
                }
            }
        }
        this.N = this.dimension();
        this.blanki = f;
        this.blankj = c;
    }

}

并得到以下错误:

文件:C:\Users\cbozanic\algs4\Board.java [行:28] 错误:f 无法解析为变量 文件:C:\Users\cbozanic\algs4\Board.java [行:29] 错误:c 无法解析为变量 文件:C:\Users\cbozanic\algs4\Board.java [行:159] 错误:局部变量s可能没有被初始化

我真的不明白我做错了什么!任何帮助将不胜感激。

【问题讨论】:

  • 这是因为您已将fc 声明为循环内的变量。此外,我强烈建议您使用如此先进的 IDE - 它会帮助您摆脱此类错误。

标签: java variables private final


【解决方案1】:

fcfor 循环的范围内定义。它们在外面是不可见的:

this.blocks = new int[blocks.length][blocks.length];

for(i = 0; i < blocks.length; i++){
    for(j = 0; j < blocks.length; j++){
            int f = i;
            int c = j;
    } //From this point, f and c are not defined anymore
}
}
this.N = this.dimension();
this.blanki = f; //Here, f does not exist
this.blankj = c; //Here, c does not exist

如果您想使用 f 和 c,请在循环之前声明它们:

int f = ...
int c = ...

 for(i = 0; i < blocks.length; i++){
    for(j = 0; j < blocks.length; j++){
            f = ...;
            c = ...;
    }
}

对于消息The local variable s may not have been initialized,表示您声明并使用了该变量而没有对其进行初始化。例如:

int s; //For example, int s = 0; would make sense.
s++;

注意:类属性在创建新实例时采用默认值,但局部变量保持“未初始化”状态。

【讨论】:

    【解决方案2】:

    变量f在此范围内不可见:

    this.blanki = f;
    

    考虑在方法的开头添加int f = 0;

    同样适用于变量c

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-27
      • 1970-01-01
      • 1970-01-01
      • 2011-02-26
      相关资源
      最近更新 更多