我的编译器警告我,当我去分配它时,一个实例变量,一个2d int [] []数组可能没有被初始化。
我理解编译器为什么会这么想,因为它是在double if语句中初始化的。但是,第一个if在布尔值上初始化为true,第二个if在else上抛出异常。我对程序的逻辑充满信心,但编译器显然不是。
有没有人有任何克服此类问题的提示?我不想以其他方式初始化变量,因为它意味着是最终的。
关注的变量是电路板变量。以下是包含变量的对象的构造函数的一部分。
try {
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
boolean first = true;
int lineCount = 0;
String line;
while ((line = br.readLine()) != null) {
String lineParts[] = line.split(" ");
if (first) {
if (lineParts.length == 2) {
this.xSize = Integer.parseInt(lineParts[0]);
this.ySize = Integer.parseInt(lineParts[1]);
board = new int[this.ySize][this.xSize];
first = false;
} else { throw new RuntimeException(); }
} else {
lineCount++;
if (lineParts.length == this.xSize) {
for (int i = 0; i < this.xSize; i++) {
board[lineCount][i] = Integer.parseInt(lineParts[i]);
}
} else throw new RuntimeException();
}
}
br.close();
if (lineCount != this.ySize) throw new RuntimeException();
}
答案 0 :(得分:1)
实际上,编译器无法解释循环逻辑,足以知道final
变量在使用前已初始化。
你需要将第一行的处理移出循环 - 这无论如何都是合理的,因为第一行和后续行的循环内容几乎完全不同:
try {
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
int lineCount = 0;
String line;
line = br.readLine();
if (line != null) {
String lineParts[] = line.split(" ");
if (lineParts.length == 2) {
this.xSize = Integer.parseInt(lineParts[0]);
this.ySize = Integer.parseInt(lineParts[1]);
board = new int[this.ySize][this.xSize];
} else {
throw new RuntimeException();
}
while ((line = br.readLine()) != null) {
String lineParts[] = line.split(" ");
lineCount++;
if (lineParts.length == this.xSize) {
for (int i = 0; i < this.xSize; i++) {
board[lineCount][i] = Integer.parseInt(lineParts[i]);
}
} else {
throw new RuntimeException();
}
}
}
br.close();
if (lineCount != this.ySize) throw new RuntimeException();
}
注意:此代码保留了先前代码的行为,即它不计算第一行。我猜它特别包括不计算它。 : - )
附注:我强烈建议在该代码中使用try-with-resources,不仅仅是为了获得最佳实践,还因为在抛出异常时没有关闭文件:
try (
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
) {
int lineCount = 0;
String line;
line = br.readLine();
if (line != null) {
String lineParts[] = line.split(" ");
if (lineParts.length == 2) {
this.xSize = Integer.parseInt(lineParts[0]);
this.ySize = Integer.parseInt(lineParts[1]);
board = new int[this.ySize][this.xSize];
} else {
throw new RuntimeException();
}
while ((line = br.readLine()) != null) {
String lineParts[] = line.split(" ");
lineCount++;
if (lineParts.length == this.xSize) {
for (int i = 0; i < this.xSize; i++) {
board[lineCount][i] = Integer.parseInt(lineParts[i]);
}
} else {
throw new RuntimeException();
}
}
}
if (lineCount != this.ySize) throw new RuntimeException();
}