Java 打印矩阵项程序

编写一个Java程序来打印矩阵项或元素或值,并附带示例。或者编写一个Java程序来显示多维数组项。

通常,我们可以使用任何可用的循环来显示矩阵项。在这个Java示例中,我们声明了一个整数项矩阵。接下来,我们使用For Loop来迭代行和列元素。我们在for循环中使用format函数来显示或打印矩阵项作为输出。

public class PrintMatrixItems {
	
	public static void main(String[] args) {
		
		int[][] x = {{10, 20, 30}, {40, 50, 60}, {70, 80, 90}};
		
		int i, j;
		
		System.out.println("------ The Matrix items ------");
		
		for(i = 0; i < x.length; i++)
		{
			for(j = 0; j < x[0].length; j++)
			{
				System.out.format("\nThe Matrix Item at " + i + "," + j +
						" position = " + x[i][j]);
			}
			System.out.println("");
		}
	}
}
Java program to print Matrix items

Java打印矩阵项示例2

此显示矩阵项的程序与上述相同。但是,此Java代码允许用户通过for循环输入行数、列数和矩阵项。

import java.util.Scanner;

public class PrintMatrixItems {
	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 Rows and Columns :  ");
		rows = sc.nextInt();
		columns = sc.nextInt();
		
		int[][] arr1 = new int[rows][columns];
		
		System.out.println("\n Please Enter the arr1 items :  ");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				arr1[i][j] = sc.nextInt();
			}		
		}

		System.out.println("\n---The total items are--- ");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				System.out.format("\nThe Item at " + i + "," + j +
						" position = " + arr1[i][j]);
			}
		}
	}
}
 Please Enter Rows and Columns :  
3 3

 Please Enter the arr1 Items :  
11 22 33
44 55 66
77 88 99

---The total items are--- 

The Item at 0,0 position = 11
The Item at 0,1 position = 22
The Item at 0,2 position = 33
The Item at 1,0 position = 44
The Item at 1,1 position = 55
The Item at 1,2 position = 66
The Item at 2,0 position = 77
The Item at 2,1 position = 88