我有这段代码:
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 [line:28] 错误:f无法解析为变量 文件:C:\ Users \ cbozanic \ algs4 \ Board.java [line:29] 错误:c无法解析为变量 文件:C:\ Users \ cbozanic \ algs4 \ Board.java [line:159] 错误:局部变量s可能尚未初始化
我真的不知道我做错了什么!任何帮助将不胜感激。
答案 0 :(得分:1)
f
和c
在for
循环的范围内定义。它们在外面是不可见的:
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++;
注意:类属性在创建新实例时采用默认值,但局部变量保持“未初始化”状态。
答案 1 :(得分:0)
变量f
在此范围内不可见:
this.blanki = f;
考虑在方法的开头添加int f = 0;
。
同样适用于变量c
。