2 回答
TA贡献1824条经验 获得超6个赞
您的问题是您正在将一个实例视为Matrix一个数组;它不是。它有一个数组。如果您想操作newArray实例的内部数组(我强烈建议将该变量重命名为newMatrix),那么您可以通过访问newArray.array.
TA贡献1765条经验 获得超5个赞
如果我在这里得到你就是你想要的:
public class Matrix {
private final int[][] array;
private final int size1;
private final int size2;
Matrix(int size1, int size2) {
this.size1 = size1;
this.size2 = size2;
this.array = new int[size1][size2];
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (int[] arr: array)
builder.append(Arrays.toString(arr) + "\n");
return "Matrix{" +
"array=\n" + builder +
'}';
}
Matrix(int[][] color) {
this.size1 = color.length;
this.size2 = color[0].length;
this.array = new int[size1][size2];
for (int row = 0; row < size1; row++) {
for (int column = 0; column < size2; column++) {
this.array[row][column] = color[row][column];
}
}
}
public Matrix flipVertically() {
int start = 0, end = size1 - 1;
while (start < end) {
int[] tmp = array[start];
array[start] = array[end];
array[end] = tmp;
start++;
end--;
}
return this;
}
public static void main(String[] args) {
Matrix matrix = new Matrix(new int[][]{{1,2,3}, {4,5,6}, {7,8,9}});
System.out.println(matrix.flipVertically());
matrix = new Matrix(new int[][]{{1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}});
System.out.println(matrix.flipVertically());
matrix = new Matrix(new int[][]{{1}});
System.out.println(matrix.flipVertically());
matrix = new Matrix(new int[][]{{1},{2},{3}});
System.out.println(matrix.flipVertically());
}
输出:
Matrix{array=
[7, 8, 9]
[4, 5, 6]
[1, 2, 3]
}
Matrix{array=
[10, 11, 12]
[7, 8, 9]
[4, 5, 6]
[1, 2, 3]
}
Matrix{array=
[1]
}
Matrix{array=
[3]
[2]
[1]
}
要回答您的问题:
如上所述,您正在创建 Matrix 类的新实例,而不是数组。此外,这
newArray[row][column]=array[size1][size2];不是您在 java 中复制数组的方式,尽管我认为您根本不需要复制它 - 请参阅我的实现。无论如何,如果要复制您的数组,请参阅此 在 java 中复制 2d 数组您可以这样创建矩阵类型的变量:
Matrix matrix = new Matrix(new int[][]{{1,2,3}, {4,5,6}, {7,8,9}});. 在我的代码中,我只是返回thiswitch 是对自身的引用。
PS 改进代码的建议:添加 getter 和 setter,如果没有理由保留构造函数,则将其公开friendly,当您将空数组传递给构造函数时检查是否存在极端情况......
添加回答
举报
