【问题标题】:2D Array flip vertically and horizontally2D Array 垂直和水平翻转
【发布时间】:2017-06-12 09:40:31
【问题描述】:

我有这个方法可以将数组旋转 90 度。我想垂直和水平翻转(我用不同的按钮绑定它们)。方法如下。

private void Rotate90() {
    String[][] temp = new String[totalX][totalY];
    for (int y = 0; y < totalY; y++) {
        for (int x = 0; x < totalX; x++) {
            temp[x][y] = fields[x][y].getText();
        }
    }
    for (int y = 0; y < totalY; y++) {
        for (int x = 0; x < totalX; x++) {
            fields[x][y].setText(temp[y][x]);
        }
    }
    Draw();
}

【问题讨论】:

  • 请帮助我输入和输出示例
  • @SaurabhJhunjhunwala 你是什么意思?

标签: java arrays loops


【解决方案1】:

@khriskooper 代码包含一个明显的错误:它翻转数组两次,即实际上什么都不做。要翻转数组,您应该只迭代 一半 的索引。试试这样的:

private void flipHorizontally() {
    for (int y = 0; y < totalY; y++) {
        for (int x = 0; x < totalX/2; x++) {
            String tmp = fields[totalX-x-1][y].getText();
            fields[totalX-x-1][y].setText(fields[x][y].getText());
            fields[x][y].setText(tmp);
        }
    }
}


private void flipVertically() {
    for (int x = 0; x < totalX; x++) {
        for (int y = 0; y < totalY/2; y++) {
            String tmp = fields[x][totalY - y - 1].getText();
            fields[x][totalY - y - 1].setText(fields[x][y].getText());
            fields[x][y].setText(tmp);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2016-07-17
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 2016-07-29
    • 1970-01-01
    • 2019-09-04
    相关资源
    最近更新 更多