2016-05-15 61 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类什么的。