2016-05-15 51 views
0

大約兩週前我開始學習Java,所以請不要猶豫。 我正在做這個程序與一個二維數組(圖片),我想旋轉90度(已完成,測試,它的工作)和180.我的方法是無效的,我想用90度一個兩次(組成?)在180度之一,但它不起作用。void方法中使用的void方法的組成? (Java)

這是我的90方法:

public void rotate90(){ 
     for (int r = 0; r < w; r++) { 
      for (int c = 0; c < h; c++) { 
       imageMatrix[c][w-r-1] = imageMatrix[r][c]; 
      } 
     } 

public void rotate180(){ 
     rotate90(rotate90()); // my idea was to rotate again the already rotated matrix, but since rotate90 is void it doesn't work 
} 

有沒有一種方法,我可以做到這一點?用void函數?

在此先感謝!

回答

3

方法rotate90()沒有參數。其實這不是正確的方法。

第一種方法是寫出來。

rotate90(); 
rotate90(); 

或者使用for-cycle

for (int i=0; i<2; i++) { 
    rotate90(); 
} 

但是這裏是旋轉它,你有多少次想只有一個方法,一個方法:

public void rotate90(int n) { 
    for (int i=0; i<n; i++) { 
     for (int r=0; r<w; r++) { 
      for (int c=0; c<h; c++) { 
       imageMatrix[c][w-r-1] = imageMatrix[r][c]; 
      } 
     } 
    } 

然後是rotate180()方法:

public void rotate180(){ 
    rotate90(2); // rotate by 90 two times 
} 
+0

由於某種原因,當我給rotate90調用兩次時,它不起作用...你能告訴我更多關於循環方法嗎?謝謝。 –

+0

它不旋轉180,只有90,我不知道爲什麼。是否有可能將矩陣旋轉90度,然後再旋轉相同的矩陣,而不是旋轉新的矩陣?我認爲我只是想另一種方式,不用調用rotate90。再次感謝您的幫助! –

2

你只需要調用該方法兩次。你不能做的就是撥打rotate90(),返回值爲rotate90這就是你提出的代碼正在做的事情,因爲這個方法不帶參數或返回一個值。

1

如果你想一次調用它,你可以把它作爲一個參數

public void rotate90nTimes(int n){ 
    for (int times = 0; times < n; times++) { 
     for (int r = 0; r < w; r++) { 
      for (int c = 0; c < h; c++) { 
       imageMatrix[c][w-r-1] = imageMatrix[r][c]; 
      } 
     } 
    } 
} 

PS: 如果你想使用它作爲rotate90(rotate90)你需要返回的矩陣,而不是使功能無效。

1

您的rotate90()直接在全局變量上工作,所以您的rotate180()也會。

public void rotate180(){ 
    rotate90(); 
    rotate90(); 
} 

但是,我建議你使用一些參數和返回值,如果嚴格需要只使用全局變量。另外,我不確定你的算法是否正確,我會這樣做。

public static int[][] rotate90(int[][] matrix){ 
    int [][] newMatrix = new int[matrix[0].length][matrix.lenght]; 

    for (int r = 0; r < w; r++) { 
     for (int c = 0; c < h; c++) { 
      newMatrix[c][w-r-1] = matrix[r][c]; 
     } 
    } 
    return newMatrix; 
} 

public static int[][] rotate180(){ 
    return rotate90(rotate90()); 
} 

沒有必要將它們設置爲static,但因爲他們並不需要一個對象來工作,你可以將它們移動到Utils類什麼的。