【问题标题】:Mirroring 2D Arrays镜像二维阵列
【发布时间】:2015-03-26 16:24:07
【问题描述】:

您好,我正在尝试编写一个采用二维数组并像这样镜像它的代码,

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;
    }
}
}

我的程序可以运行,但是它返回的结果相反

input:        and get the output like so:  
  123                                      789
  456                                      456
  789                                      123

我做错了什么..?

【问题讨论】:

  • 您正在反转数组的第一个维度,而不是第二个维度。您需要将for 中的mirror 循环包裹在另一个for 循环中,并适当调整索引。

标签: java arrays multidimensional-array mirror


【解决方案1】:

您正在反转数组的第一个维度(“行”),而不是第二个维度(“列”)。

您需要将镜像中的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;
    }
  }
}

【讨论】:

  • 顺便说一下,你不应该使用这样的逆变数组类型。阅读 Effective Java 2nd Ed Item 25,“Prefer lists to arrays”,了解破坏这样的事情是多么容易。
  • 不应该是“int j = 0; j
  • 已修复。这将教我尝试在答案窗口中使用代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-11
  • 1970-01-01
  • 2015-01-30
  • 2011-01-03
  • 2012-04-01
相关资源
最近更新 更多