我有这样的代码:
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可能尚未初始化
我真的不明白我到底做错了什么!任何帮助都将不胜感激。
发布于 2015-03-19 22:34:31
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++;注释:创建新实例时,类属性采用默认值,但局部变量保持“未初始化”状态。
发布于 2015-03-19 22:34:59
变量f在此范围内不可见:
this.blanki = f;考虑在方法的开头添加int f = 0;。
变量c也是如此。
https://stackoverflow.com/questions/29147214
复制相似问题