以下代码片段的目的是创建矩阵的实例,然后计算nxn矩阵的行列式。但是,方法computeDet
将不会返回,因为发生以下错误:value cannot be resolved to a variable
。这是为什么?
**从here编辑的决定性代码(此代码确实有效 - 无错误)
public class MatrixArrayCR {
long[][] matrix;
public MatrixArrayCR(long[] arr) {
double len = Math.sqrt(arr.length);
int counter = 0;
for (int i=0; i==len; i++) {
for (int j=0; j==len; j++) {
matrix[i][j] = arr[counter];
counter++;
}
}
}
// determinant method edited from code off http://www.coderanch.com/t/446179/java/java/Learning-Project
public long determinant() {
return computeDet(matrix);
}
public long computeDet(long[][] matrix) {
int matrixSize = matrix.length;
if (matrixSize==2) {
return matrix[0][0]*matrix[1][1]-matrix[0][1]*matrix[1][0];
} else {
long value = 0;
for (int i=0; i<matrixSize; i++) {
long[][] minor=generateMinor(matrix,0,i);
value += (sgn(i)*matrix[0][i]*computeDet(minor));
}
} return value; //ERROR HERE
}
private int sgn(int n) {
if (n%2==0) {
return 1;
} else {
return -1;
}
}
private long[][] generateMinor(long[][] matrix, int row, int column) {
int matrixSize = matrix.length;
int minorSize = matrixSize -1;
int counterOne = 0;
int counterTwo = 0;
long[][] minor = new long[minorSize][minorSize];
for (int i=0; i<matrixSize; i++) {
if (i==row) {
continue;
} for (int j=0; j<matrixSize; j++) {
if (j==column) {
continue;
} minor[counterOne][counterTwo] = matrix[i][j];
++ counterTwo;
} ++counterOne;
counterTwo = 0;
} return minor;
}
}
答案 0 :(得分:2)
value
是一个局部变量,即它只在声明的块中可见。由于您在else块中声明了值并尝试将其返回到此块之外,因此会出现此错误。
return语句应该在else块中。我:
public long computeDet(long[][] matrix) {
int matrixSize = matrix.length;
if (matrixSize==2) {
return matrix[0][0]*matrix[1][1]-matrix[0][1]*matrix[1][0];
} else {
long value = 0;
for (int i=0; i<matrixSize; i++) {
long[][] minor=generateMinor(matrix,0,i);
value += (sgn(i)*matrix[0][i]*computeDet(minor));
}
return value;
}
}
答案 1 :(得分:1)
value变量在if或else块内声明,仅在声明的块中可见。如果您希望它在方法的末尾可见,请在方法的开头,if / else块之前声明它。
public long computeDet(long[][] matrix) {
long value = 0L;
int matrixSize = matrix.length;
if (matrixSize==2) {
value = matrix[0][0]*matrix[1][1]-matrix[0][1]*matrix[1][0];
} else {
for (int i=0; i<matrixSize; i++) {
long[][] minor=generateMinor(matrix,0,i);
value += (sgn(i)*matrix[0][i]*computeDet(minor));
}
}
return value;
}
或者从else块的里面返回它:
public long computeDet(long[][] matrix) {
int matrixSize = matrix.length;
if (matrixSize==2) {
return matrix[0][0]*matrix[1][1]-matrix[0][1]*matrix[1][0];
} else {
long value = 0;
for (int i=0; i<matrixSize; i++) {
long[][] minor=generateMinor(matrix,0,i);
value += (sgn(i)*matrix[0][i]*computeDet(minor));
}
return value; //ERROR HERE
} // this guy moved
}