有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

void方法中使用的void方法的数组组成?(爪哇)

我大约两周前开始学习Java,所以请不要挑剔。 我用一个二维数组(一张图片)来做这个程序,我想把它旋转90度(已经做过,测试过了,可以正常工作)和180度。我的方法是无效的,我想使用90度1两次(合成?)在180度方向,但它不起作用

这是我的方法:

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
}

我有办法做到这一点吗?用空函数

提前谢谢


共 (4) 个答案

  1. # 1 楼答案

    您只需要调用该方法两次。您不能做的是使用返回值rotate90()调用rotate90,这就是您建议的代码所做的,因为该方法不接受参数或返回值

  2. # 2 楼答案

    如果只想调用一次,可以将其作为参数传递

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

    附言: 如果确实要将其用作rotate90(rotate90),则需要返回矩阵,而不是将函数设为void

  3. # 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
    }
    
  4. # 4 楼答案

    您的rotate90()直接处理全局变量,因此您的rotate180()也会处理全局变量

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

    但是,如果我建议严格使用一些全局变量,那么我将使用ESARY。另外,我不确定你的算法是否正确,我会这样做

    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类或其他地方