簡體   English   中英

作廢法中作廢法的組成? (Java)

[英]Composition of void method used in void method? (Java)

我大約兩周前開始學習Java,所以請不要猶豫。 我正在使用二維數組(圖片)執行此程序,我想將其旋轉90度(已經完成,經過測試,可以正常工作)和180度。我的方法無效,我想使用90度旋轉在180度中兩次(組成?),但不起作用。

這是我的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
}

有辦法嗎? 具有空函數?

提前致謝!

方法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
}

您只需要調用該方法兩次。 您不能執行的操作是調用rotate90() ,返回值rotate90 ,這是您建議的代碼正在執行的操作,因為該方法不帶參數也不返回值。

您的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類或其他類。

如果您只想調用一次,則可以將其作為參數傳遞

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),則需要返回矩陣,並且不要將函數設為void。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM