Java 程序检查两个矩阵是否相等

编写一个 Java 程序来检查两个矩阵是否相等。或者如何编写一个 Java 程序来判断两个多维矩阵是否相等,并附有示例。

在此 Java 矩阵相等示例中,我们声明了两个 2*2 的整数矩阵。接下来,我们使用 for 循环遍历矩阵的项。在 for 循环 中,我们使用 If 语句 来检查矩阵 x 中的每个项是否不等于矩阵 y 中的项。

如果为真,我们将 isEqual 值更改为 0 并应用 break 语句退出循环。接下来,我们在 If Else 语句 中使用 isEqual 变量来根据 isEqual 值打印输出。

public class MatrixEqualOrNot {
	public static void main(String[] args) {
		int[][] x = {{1, 2}, {3, 4}};
		int[][] y = {{1, 2}, {3, 4}};
		
		int i, j, isEqual = 1;
		
		for(i = 0; i < x.length; i++)
		{
			for(j = 0; j < x[0].length; j++)
			{
				if(x[i][j] != y[i][j]) {
					isEqual = 0;
					break;
				}
			}
		}
		if(isEqual == 1) {
			System.out.println("\nMatrix x is Equal to Matrix y");
		}
		else {
			System.out.println("\nMatrix x is Not Equal to Matrix y");
		}
	}
}

Java 矩阵相等输出

Matrix x is Equal to Matrix y

Java 程序示例 2:检查两个矩阵是否相等

Java 矩阵相等代码与上面相同。但是,此用于多维相等的 Java 代码 允许用户输入行数、列数和 矩阵 项。

import java.util.Scanner;

public class MatrixEqualOrNot {
	private static Scanner sc;
	
	public static void main(String[] args) {
		int i, j, rows, columns, isEqual = 1;	
		
		sc= new Scanner(System.in);	
		
		System.out.println("\n Enter Matrix Rows & Columns :  ");
		rows = sc.nextInt();
		columns = sc.nextInt();
		
		int[][] x = new int[rows][columns];
		int[][] y = new int[rows][columns];
		
		System.out.println("\n Enter the First Matrix Items :  ");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				x[i][j] = sc.nextInt();
			}		
		}
		
		System.out.println("\n Enter the Second Matrix Items :  ");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				y[i][j] = sc.nextInt();
			}		
		}
		
		for(i = 0; i < x.length; i++)
		{
			for(j = 0; j < x[0].length; j++)
			{
				if(x[i][j] != y[i][j]) {
					isEqual = 0;
					break;
				}
			}
		}
		if(isEqual == 1) {
			System.out.println("\nMatrix x is Equal to Matrix y");
		}
		else {
			System.out.println("\nMatrix x is Not Equal to Matrix y");
		}
	}
}
Java Program to Check Matrices are Equal Example

我来试试不同的矩阵。

 Enter Matrix Rows & Columns :  
2 2

 Enter the First Matrix Items :  
1 2
3 4

 Enter the Second Matrix Items :  
1 3
3 4

Matrix x is Not Equal to Matrix y