编写一个Java程序来查找矩阵是否为单位矩阵,并附带一个示例。Java单位矩阵是一个方形矩阵,其主对角线元素为1,所有其他元素为零。
在此Java单位矩阵示例中,我们声明了一个3x3的整数矩阵。接下来,我们使用for循环遍历矩阵。在for循环内部,我们使用If语句来检查对角线是否为1,非对角线元素是否为零。如果为真,我们将Flag值更改为0,并应用break语句退出循环。接下来,我们使用If Else语句根据Flag值打印输出。
public class IdentityMatrix {
public static void main(String[] args) {
int i, j, Flag = 1;
int[][] arr = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
for(i = 0; i < 3 ; i++)
{
for(j = 0; j < 3; j++)
{
if(arr[i][j] != 1 && arr[j][i] != 0) {
Flag = 0;
break;
}
}
}
if(Flag == 1) {
System.out.println("\nMatrix is an Identity Matrix");
}
else {
System.out.println("\nMatrix is Not an Identity Matrix");
}
}
}
Java单位矩阵输出
Matrix is an Identity Matrix
让我稍微更改矩阵并检查单位矩阵。 int[][] arr = {{1, 0, 0}, {0, 1, 1}, {0, 0, 1}};
Matrix is Not an Identity Matrix
Java程序查找矩阵是否为单位矩阵示例2
这个Java单位矩阵代码与上面的相同。但是,这个Java代码允许用户输入行数、列数和矩阵元素。
import java.util.Scanner;
public class IdentityMatrix {
private static Scanner sc;
public static void main(String[] args) {
int i, j, rows, columns, Flag = 1;
sc= new Scanner(System.in);
System.out.println("\n Please Enter Identity Matrix Rows and Columns : ");
rows = sc.nextInt();
columns = sc.nextInt();
int[][] arr = new int[rows][columns];
System.out.println("\n Please Enter the Identity Matrix Items : ");
for(i = 0; i < rows; i++) {
for(j = 0; j < columns; j++) {
arr[i][j] = sc.nextInt();
}
}
for(i = 0; i < rows ; i++)
{
for(j = 0; j < columns; j++)
{
if(arr[i][j] != 1 && arr[j][i] != 0) {
Flag = 0;
break;
}
}
}
if(Flag == 1) {
System.out.println("\nMatrix is an Identity Matrix");
}
else {
System.out.println("\nMatrix is Not an Identity Matrix");
}
}
}

我们还可以使用Else If语句来检查给定的矩阵是否为单位矩阵。在此Java单位矩阵示例中,我们将上面示例中的If语句替换为Else If。
public class IdentityMatrix {
public static void main(String[] args) {
int i, j, Flag = 1;
int[][] arr = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
for(i = 0; i < 3 ; i++)
{
for(j = 0; j < 3; j++)
{
if(i == j && arr[j][i] != 1) {
Flag = 0;
}
else if(i != j && arr[j][i] != 0) {
Flag = 0;
}
}
}
if(Flag == 1) {
System.out.println("\nMatrix is an Identity Matrix");
}
else {
System.out.println("\nMatrix is Not an Identity Matrix");
}
}
}
Java单位矩阵输出
Matrix is an Identity Matrix
在这里,我们将尝试使用错误的数组。 int[][] arr = {{1, 0, 0}, {0, 1, 1}, {0, 0, 1}};
Matrix is Not an Identity Matrix