我有这个代码:
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 可能尚未初始化
我真的不明白我做错了什么!任何帮助将不胜感激。
最佳答案
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 = ...;
}
}
对于消息局部变量 s 可能尚未初始化
,这意味着您声明并使用了该变量而没有对其进行初始化。例如:
int s; //For example, int s = 0; would make sense.
s++;
注意:创建新实例时,类属性采用默认值,但局部变量保持“未初始化”状态。
关于java - 私有(private)最终 int 空白;私有(private)最终int空白j;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29147214/