Java 镜像二维阵列
嗨,我正在尝试制作一个代码,它接受一个2d数组并像这样镜像它Java 镜像二维阵列,java,arrays,multidimensional-array,mirror,Java,Arrays,Multidimensional Array,Mirror,嗨,我正在尝试制作一个代码,它接受一个2d数组并像这样镜像它 input: and get the output like so: 123 321 456 654 789 987 我有这部分代码: public static void mirro
input: and get the output like so:
123 321
456 654
789 987
我有这部分代码:
public static void mirror(Object[][] theArray) {
for(int i = 0; i < (theArray.length/2); i++) {
Object[] temp = theArray[i];
theArray[i] = theArray[theArray.length - i - 1];
theArray[theArray.length - i - 1] = temp;
}
}
}
我做错了什么?您正在反转数组的第一个维度(“行”),而不是第二个维度(“列”) 您需要将镜像中的for循环包装到另一个for循环中,并适当地调整索引
public static void mirror(Object[][] theArray) {
for (int j = 0; j < theArray.length; ++j) { // Extra for loop to go through each row in turn, performing the reversal within that row.
Object[] row = theArray[j];
for(int i = 0; i < (row.length/2); i++) {
Object temp = row[i];
row[i] = theArray[j][row.length - i - 1];
row[row.length - i - 1] = temp;
}
}
}
公共静态无效镜像(对象[][]阵列){
for(int j=0;j
您正在反转数组的第一个维度,而不是第二个维度。您需要将for
循环包装在mirror
中的另一个for循环中,并适当调整索引。顺便说一下,您不应该像这样使用逆变数组类型。阅读有效的Java第二版第25项“更喜欢列表而不是数组”,了解打破这种情况有多容易。它是否应该是“int j=0;jpublic static void mirror(Object[][] theArray) {
for (int j = 0; j < theArray.length; ++j) { // Extra for loop to go through each row in turn, performing the reversal within that row.
Object[] row = theArray[j];
for(int i = 0; i < (row.length/2); i++) {
Object temp = row[i];
row[i] = theArray[j][row.length - i - 1];
row[row.length - i - 1] = temp;
}
}
}