Java 如何打印下三角矩阵
在Java中,数组是一个对象。它是一种非基本数据类型,用于存储相同数据类型的值。Java中的矩阵实际上就是多维数组,表示多个行和列。
三角形矩阵 - 如果矩阵的对角线上方或下方的所有元素都是零,则称其为三角形矩阵。
下三角矩阵 - 如果矩阵的对角线上方的所有元素都是零,则称其为下三角矩阵。
我们要打印下三角矩阵。
让我们开始吧!
显示一些示例
示例1
给定矩阵 =
21 22 23
24 25 26
27 28 29
下面是英文翻译成中文的结果,保留HTML格式:
给定矩阵的下三角形矩阵为-
21 0 0
24 25 0
27 28 29
示例2
给定矩阵 =
921 222 243 432
124 745 256 657
237 258 429 345
176 453 756 843
给定矩阵的下三角矩阵为 –
921 0 0 0
124 745 0 0
237 258 429 0
176 453 756 843
示例3
给定矩阵 =
1 2 3
4 5 6
7 8 9
给定矩阵的下三角矩阵为−
1 0 0
4 5 0
7 8 9
步骤
步骤-1
- 步骤-1 - 初始化一个二维数组矩阵来表示输入矩阵。
-
步骤-2 - 使用两个嵌套循环遍历矩阵的每个元素。外部循环遍历矩阵的行,内部循环遍历每行的列。
-
步骤-3 - 检查当前列是否大于当前行。如果是,则将当前元素设置为0。
-
步骤-4 - 打印当前元素。
-
步骤-5 - 在内部循环结束后,移动到下一行以打印下一行。
步骤-2
-
步骤-1 - 初始化一个二维数组矩阵来表示输入矩阵。
-
步骤-2 - 使用IntStream循环遍历矩阵的行。
-
步骤-3 - 使用另一个IntStream循环遍历每行的列。
-
步骤-4 - 检查当前列是否大于当前行。如果是,则将当前元素设置为0。
-
步骤-5 - 打印当前元素。在内部循环结束后,移动到下一行以打印下一行。
语法
1. The Matrix.length() 方法在Java中返回给定矩阵的长度。
下面是它的语法:
inputMatrix.lenght
其中,’inputMatrix’指的是给定的矩阵。
2. IntStream.range() 是Java中的一个方法,用于生成从startInclusive到endExclusive – 1的连续整数流。
IntStream.range(startInclusive, endExclusive)
它可以用来对一组整数执行操作。例如,在第二段代码中,它被用来循环遍历矩阵的行和列。
然后,在流上调用方法 forEach ,对流中的每个元素执行一个动作。
多种方法
我们提供了不同的方法来解决问题。
- 使用嵌套循环
-
使用流
让我们逐一查看程序及其输出。
方法1:使用嵌套循环
在这种方法中,矩阵元素将在程序中初始化。然后通过将矩阵作为参数调用用户定义的方法,并根据算法使用嵌套循环的方法来打印给定矩阵的下三角矩阵。
示例
public class Main {
public static void main(String[] args) {
int[][] inputMatrix = {{11, 22, 33, 44},
{55, 66, 77, 88},
{99, 10, 11, 12},
{13, 14, 15, 16}};
LowerTriangularMatrix(inputMatrix);
}
public static void LowerTriangularMatrix(int[][] mat) {
System.out.println("Lower triangular matrix of given matrix is: ");
// initiate the loop to check through the rows
for (int a = 0; a < mat.length; a++) {
// then check through each columns
for (int b = 0; b < mat[a].length; b++) {
// If the column is greater than the row, set the element to 0
if (b > a) {
mat[a][b] = 0;
}
// Print the current element
System.out.print(mat[a][b] + " ");
}
System.out.println();
}
}
}
输出
Lower triangular matrix of given matrix is:
11 0 0 0
55 66 0 0
99 10 11 0
13 14 15 16
方式2:使用流进行处理
在这种方法中,矩阵元素将在程序中进行初始化。然后通过传递矩阵作为参数调用用户定义的方法,然后根据算法,在方法内部使用流方法打印给定矩阵的下三角矩阵。
示例
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
int[][] inputMatrix = {{12, 32, 13},
{5, 6, 7},
{9, 10, 11}};
//call the user-defined method
lowerTriangularMatrix(inputMatrix);
}
public static void lowerTriangularMatrix(int[][] mat) {
System.out.println("Lower triangular matrix of given matrix is: ");
// Use IntStream to loop through the rows of the matrix
IntStream.range(0, mat.length)
.forEach(a -> {
// Use IntStream to loop through the columns of the current row
IntStream.range(0, mat[a].length)
.forEach(b -> {
// If the column is greater than the row, set the element to 0
if (b > a) {
mat[a][b] = 0;
}
// Print the current element
System.out.print(mat[a][b] + " ");
});
System.out.println();
});
}
}
输出
Lower triangular matrix of given matrix is:
12 0 0
5 6 0
9 10 11
在这篇文章中,我们使用Java编程语言探索了不同的方法来打印下三角形。