2017-06-12 106 views
0

我有這種方法可以將陣列旋轉90度。我想要垂直和水平翻轉(我用不同的按鈕綁定它們)。這是方法。2D陣列垂直和水平翻轉

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(); 
} 
+0

請幫我與樣品的輸入和輸出 –

+0

@SaurabhJhunjhunwala你是什麼意思? – Nicz

回答

2

@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); 
     } 
    } 
} 
+0

是的,你是對的! – khriskooper

+0

這一個工作。謝謝 – Nicz