我应该创建一个矩阵并将其拆分为3个方法,其中第一个将读取矩阵,第二个将打印矩阵,第三个将交换对角线。读取矩阵有效但我试图将参数传递给其他方法,因此它们也可以工作,但是当我在主类中调用它们时,它不起作用。
public static void readMatrix() {
Random rand = new Random();
Scanner in = new Scanner(System.in);
System.out.println("Please insert how many rows and columns you want for matrix");
int ColumnsAndRows = in.nextInt();
int matrix[][] = new int[ColumnsAndRows][ColumnsAndRows];
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = rand.nextInt(ColumnsAndRows * ColumnsAndRows) + 1;
}
}
}
public int[][] printMatrix(int matrix[][]) {
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println("");
}
return matrix;
}
public int[][] swapDiagonals(int ColumnsAndRows, int matrix[][]) {
for (int i = 0; i < ColumnsAndRows; i++) {
int temp = matrix[i][i];
matrix[i][i] = matrix[i][ColumnsAndRows - i - 1];
matrix[i][ColumnsAndRows - i - 1] = temp;
}
printMatrix(matrix);
return matrix;
答案 0 :(得分:0)
int[][]
存储从readMatrix
返回的矩阵。printMatrix
和swapDiagonals
返回int[][]
是多余的。printMatrix
和swapDiagonals
成为静态,因此您可以使用main
方法调用它们。以下是一个示例:
public class Matrix {
public static int[][] readMatrix() {
Random rand = new Random();
Scanner in = new Scanner(System.in);
System.out.println("Please insert how many rows and columns you want for matrix");
int ColumnsAndRows = in.nextInt();
int matrix[][] = new int[ColumnsAndRows][ColumnsAndRows];
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = rand.nextInt(ColumnsAndRows * ColumnsAndRows) + 1;
}
}
return matrix;
}
public static void printMatrix(int matrix[][]) {
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println("");
}
}
public static void swapDiagonals(int matrix[][]) {
int ColumnsAndRows = matrix.length;
for (int i = 0; i < ColumnsAndRows; i++) {
int temp = matrix[i][i];
matrix[i][i] = matrix[i][ColumnsAndRows - i - 1];
matrix[i][ColumnsAndRows - i - 1] = temp;
}
printMatrix(matrix);
}
public static void main(String[] args) {
int[][] matrix = readMatrix();
printMatrix(matrix);
System.out.println("swapDiagonals:");
swapDiagonals(matrix);
}
}
结果:
Please insert how many rows and columns you want for matrix
4
12 10 14 5
14 8 9 13
2 15 5 16
11 9 8 10
swapDiagonals:
5 10 14 12
14 9 8 13
2 5 15 16
10 9 8 11