Java 程序交换矩阵对角线

编写一个 Java 程序来交换矩阵对角线,并附带示例,或者编写一个程序来交换二维数组的对角线。

在此示例中,我们首先使用 If 语句检查矩阵是否为方形。接下来,我们使用 for 循环迭代二维数组。我们在 for 循环中使用 temp 变量来分配矩阵对角线元素并将其与其他对角线元素交换。接下来,我们使用另一个 for 循环打印最终的矩阵。

public class InterchangeDiagonals {
	
	public static void main(String[] args) {
		
		int i, j, temp;	
		
		int[][] arr = {{15, 25, 35}, {45, 55, 65}, {75, 85, 95}};
		
		if(arr.length == arr[0].length) {
			for(i = 0; i < arr.length ; i++)
			{
				temp = arr[i][i];
				arr[i][i] = arr[i][arr.length-i-1];
				arr[i][arr.length - i - 1] = temp;
			}
			
			System.out.println("\n Matrix Items after Interchanging Diagonals are :");
			for(i = 0; i < arr.length ; i++)
			{
				for(j = 0; j < arr[0].length; j++)
				{
					System.out.format("%d \t", arr[i][j]);
				}
				System.out.print("\n");
			}
		}
		else 
		{
			System.out.println("\n Matrix you entered is not a Square Matrix");
		}
	}
}
Program to Interchange Matrix Diagonals

Java 程序交换矩阵对角线示例 2

Java 代码与上述代码相同。但是,此 代码允许用户输入行数、列数和矩阵元素。请参阅 C 语言程序交换矩阵对角线文章以逐项分析此代码。

import java.util.Scanner;

public class InterchangeDiagonals {
private static Scanner sc;

public static void main(String[] args) {

int i, j, rows, columns, temp;

sc= new Scanner(System.in);

System.out.println("\n Please Enter Interchangeable Matrix Rows and Columns : ");
rows = sc.nextInt();
columns = sc.nextInt();

int[][] arr = new int[rows][columns];

System.out.println("\n Please Enter the Items : ");
for(i = 0; i < rows; i++) {
for(j = 0; j < columns; j++) {
arr[i][j] = sc.nextInt();
}
}

if(rows == columns) {
for(i = 0; i < rows ; i++)
{
temp = arr[i][i];
arr[i][i] = arr[i][rows-i-1];
arr[i][rows-i-1] = temp;
}
System.out.println("\n Matrix Items after Interchanging Diagonals are :");
for(i = 0; i < rows ; i++)
{
for(j = 0; j < columns; j++)
{
System.out.format("%d \t", arr[i][j]);
}
System.out.print("\n");
}
}
else
{
System.out.println("\n Matrix you entered is not a Square Matrix");
}
}
}

交换矩阵对角线输出

 Please Enter Interchangeable Matrix Rows and Columns :  
3 3

 Please Enter the Items :  
10 20 30
40 50 60
70 80 90

 Matrix Items after Interchanging Diagonals are :
30 	20 	10 	
40 	50 	60 	
90 	80 	70