2D阵列垂直和水平翻转

时间:2017-06-12 09:40:31

标签: java arrays loops

我有这种方法能够将数组旋转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();
}

1 个答案:

答案 0 :(得分:3)

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

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