我正在自学一些 Java,我一直坚持创建一个二维数组,用随机值初始化它,然后创建数组的转置。

一个示例输出是:

$ java Test1 22 333 44 555 6
Enter the number of rows (1-10): 0
ERROR: number not in specified range (1-10) !
and so on until you enter the correct number of rows and columns.

原始矩阵



转置矩阵



^ 应该是最终输出。对代码的一些帮助将不胜感激!

如果行或列的数量超出指定范围,我想编写代码以生成错误消息。以及是否从命令行读取矩阵元素,而不是随机生成它们。
import java.util.Scanner;

public class Test1 {
    /** Main method */
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the number of rows (1-10): ");
        int rows = input.nextInt();
        System.out.print("Enter the number of columns (1-10): ");
        int cols = input.nextInt();

        // Create originalMatrix as rectangular two dimensional array
        int[][] originalMatrix = new int[rows][cols];

        // Assign random values to originalMatrix
        for (int row = 0; row < originalMatrix.length; row++)
            for (int col = 0; col < originalMatrix[row].length; col++) {
                originalMatrix[row][col] = (int) (Math.random() * 1000);
            }

        // Print original matrix
        System.out.println("\nOriginal matrix:");
        printMatrix(originalMatrix);

        // Transpose matrix
        int[][] resultMatrix = transposeMatrix(originalMatrix);


        // Print transposed matrix
        System.out.println("\nTransposed matrix:");
        printMatrix(resultMatrix);
    }

    /** The method for printing the contents of a matrix */
    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();
        }
    }

    /** The method for transposing a matrix */
    public static int[][] transposeMatrix(int[][] matrix) {
        // Code goes here...
    }
}

最佳答案

这是一个返回转置矩阵的 int[][] 的简单方法......

public static int[][] transposeMatrix(int[][] matrix){
    int m = matrix.length;
    int n = matrix[0].length;

    int[][] transposedMatrix = new int[n][m];

    for(int x = 0; x < n; x++) {
        for(int y = 0; y < m; y++) {
            transposedMatrix[x][y] = matrix[y][x];
        }
    }

    return transposedMatrix;
}

比打印 2D 矩阵,您可以使用这样的方法:
public static String matrixToString(int[][] a){
    int m = a.length;
    int n = a[0].length;

    String tmp = "";
    for(int y = 0; y<m; y++){
        for(int x = 0; x<n; x++){
            tmp = tmp + a[y][x] + " ";
        }
        tmp = tmp + "\n";
    }

    return tmp;
}

关于java - 从二维数组转置矩阵,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26197466/

10-11 20:30
查看更多