简体   繁体   English

如何在 java 中将二维数组的行向下移动 1?

[英]How can I shift the rows of a 2d array down by 1 in java?

What would be the most basic way to shift the rows of a 2d array in java down by 1. The first row turns into the second row, the second row turns into the third row and the last row turns into the first one.将 java 中的二维数组的行向下移动 1 的最基本方法是什么。第一行变成第二行,第二行变成第三行,最后一行变成第一行。

I tried this but it only lets me change two rows.我试过了,但它只能让我改变两行。

public static void switchRows(int[][] matrix, int K, int L){
   for (int i = 0; i < matrix[0].length; i++) {    
   // Swap two numbers
     int temp = matrix[K - 1][i];
     matrix[K - 1][i] = matrix[L - 1][i];
     matrix[L - 1][i] = temp;
   }
   // Print matrix
   for(int g = 0; g < matrix.length; g++){
      for(int b = 0; b < matrix[g].length; b++){
         System.out.print(matrix[g][b] + " ");
      }
      System.out.println();
   }
}

For this problem first, you need to create a copy of the array that represents the last row ( lastRow ).对于这个问题,您首先需要创建一个表示最后一行 ( lastRow ) 的数组副本。

After that, all values for each row (except the first row matrix[0] ) have to be overwritten with values from the previous row.之后,每一行的所有值(第一行matrix[0]除外)都必须被前一行的值覆盖。

Finally, assign the reference to the defensive copy of last row to the first row of the matrix.最后,将对最后一行防御副本的引用分配给矩阵的第一行。

public static void main(String[] args) {
        int[][] matrix = {
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}
        };
        switchRows(matrix);
        printMatrix(matrix);
    }
    public static void switchRows(int[][] matrix){
        int[] lastRow = Arrays.copyOf(matrix[matrix.length - 1], matrix[matrix.length - 1].length);
        for (int row = matrix.length - 1; row > 0; row--) {
            // assign values of the previous row to current row
            for (int col = 0; col < matrix[row].length; col++) {
                matrix[row][col] = matrix[row - 1][col];
            }
        }
        matrix[0] = lastRow;
    }
    public static void printMatrix(int[][] matrix) {
        for (int row = 0; row < matrix.length; row++){
            for(int col = 0; col < matrix[row].length; col++){
                System.out.print(matrix[row][col] + " ");
            }
            System.out.println();
        }
    }

output output

7 8 9 
1 2 3 
4 5 6 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM