Java 程序显示矩阵上三角

编写一个Java程序,通过示例显示矩阵的上三角。矩阵上三角是指对角线下方的元素都为零的方阵。

在此Java矩阵上三角示例中,我们声明了一个整数矩阵。接下来,我们使用for循环来迭代矩阵。在 for 循环 中,我们使用 If 语句 来检查列索引位置是否大于或等于行索引位置。如果为真,编译器将打印原始值;否则,它将返回0。

public class MatrixUpperTriangle {
	
	public static void main(String[] args) {
		
		int i, j;
		
		int[][] Ut_arr = {{14, 21, 31}, {44, 51, 64}, {74, 81, 94}};
		
		System.out.println("\n---The Upper Triangle of the given Matrix---");
		for(i = 0; i < 3 ; i++)
		{
			System.out.print("\n");
			for(j = 0; j < 3; j++)
			{
				if(j >= i) {
					System.out.format("%d \t", Ut_arr[i][j]);
				}
				else {
					System.out.print("0 \t");	
				}
			}
		}
	}
}
Java Program to display Matrix Upper Triangle

Java 程序显示矩阵上三角示例 2

Java 矩阵上三角代码与上面相同。但是,此 Java 代码 允许用户输入行数、列数和 矩阵 元素。

import java.util.Scanner;

public class MatrixUpperTriangle {
	private static Scanner sc;
	
	public static void main(String[] args) {
		
		int i, j, rows, columns;
		
		sc= new Scanner(System.in);
		
		System.out.println("\n Please Enter UT Matrix Rows and Columns :  ");
		rows = sc.nextInt();
		columns = sc.nextInt();
		
		int[][] arr = new int[rows][columns];
		
		System.out.println("\n Please Enter the UT Matrix Items :  ");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				arr[i][j] = sc.nextInt();
			}		
		}
		System.out.println("\n---The Upper Triangle of the given Matrix---");
		for(i = 0; i < rows ; i++)
		{
			System.out.print("\n");
			for(j = 0; j < columns; j++)
			{
				if(j >= i) {
					System.out.format("%d \t", arr[i][j]);
				}
				else {
					System.out.print("0 \t");	
				}
			}
		}
	}
}

矩阵上三角输出

 Please Enter UT Matrix Rows and Columns :  
3 3

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

---The Upper Triangle of the given Matrix---

10 	20 	30 	
0 	50 	60 	
0 	0 	90