1

I have this method that's able to rotate the array by 90 degrees. I want to be to flip vertically and horizontally (I'm binding them with different buttons). Here's the method.

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();
}
2
  • please help me with the sample input and output Commented Jun 12, 2017 at 9:43
  • @SaurabhJhunjhunwala What do you mean? Commented Jun 12, 2017 at 9:45

1 Answer 1

4

@khriskooper code contains an obvious bug: it flips array twice i.e. effectively does nothing. To flip array you should iterate only half of the indices. Try something like this:

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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.