我有这个代码:
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\als4\Board.java[行:28]错误:f无法解析为变量文件:C:\Users\cbozanic\als4\Board.java[行:29]错误:c无法解析为变量文件:C:\Users\cbozanic\als4\Board.java[行:159]错误:本地变量s可能尚未初始化
我真的不明白我做错了什么!任何帮助都将不胜感激。
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++;
注意:当创建新实例但局部变量处于"未初始化"状态时,类属性采用默认值。
变量f
在此范围内不可见:
this.blanki = f;
考虑在方法的开头添加int f = 0;
。
变量c
也是如此。