Java: Call/Return Error
I am having some trouble returning matrix data from one method to the main class, I am using:
matrix = setFalse(falseMatrix);
to call:
public static boolean[][] setFalse (boolean[][] matrix[][]) {
// Changes each value of the matrix to a false boolean value
boolean[][] falseMatrix = null;
for (int r = 0; r < ma开发者_如何转开发trix.length; r++ ) {
for (int c = 0; c < matrix[0].length; c++ ) {
falseMatrix[r][c] = false;
}
}
return falseMatrix;
}
I am getting the error that falseMatrix cannot be resolved to a variable, but when I make it a parameter I get a fatal error.
Your code is currently very confused. I suspect you want:
public static boolean[][] setFalse(boolean[][] matrix) {
// Changes each value of the matrix to a false boolean value
for (int r = 0; r < matrix.length; r++ ) {
for (int c = 0; c < matrix[r].length; c++ ) {
matrix[r][c] = false;
}
}
return matrix;
}
How you then call the method is a different matter. You need to already have a variable (or some other expression) of type boolean[][]
. Unfortunately you haven't shown us any of the context of the calling code.
change
(boolean[][] matrix[][]) {
to
(boolean[][] matrix) {
and
boolean[][] falseMatrix = null;
to
boolean[][] falseMatrix = new boolean[matrix.length][];
and insert between the two for
falseMatrix[r] = new boolean[matrix[r].length];
and finally change in 2nd for
matrix[0].length;
to
matrix[r].length;
Change:
public static boolean[][] setFalse (boolean[][] matrix[][]) {
To:
public static boolean[][] setFalse (boolean[][] matrix) {
Also, initialize your array:
//HERE
boolean[][] falseMatrix = new boolean[matrix.length];
for (int r = 0; r < falseMatrix.length; r++ ) {
//AND HERE
falseMatrix[r] = new boolean[matrix[0].length];
for (int c = 0; c < falseMatrix[r].length; c++ ) {
falseMatrix[r][c] = false;
}
}
return falseMatrix;
}
for (int r = 0; r < matrix.length; r++ ) {
for (int c = 0; c < matrix[0].length; c++ ) {
you should probably change matrix[0]
to matrix[r]
. Not sure if it solves your problem, but Im pretty sure thats what you want.
boolean[][] falseMatrix = null;
falseMatrix
is a null reference. You have to initialize it to with rows, columns before trying to keep values at it's indices.
On the first line (the calling line) you are using two different variables, falseMatrix
and matrix
, since it's giving error on falseMatrix
then I suppose it's the wrong one.
You need:
boolean[][] falseMatrix = new boolean[matrix.length][matrix[0].length];
精彩评论