Java 打印矩阵的边界元素
在本文中,我们将了解如何打印矩阵的边界元素。矩阵是按行列表示元素的结构。边界元素是指四个方向上都没有其他元素包围的元素。例如,第一行、第一列、最后一行和最后一列的元素。
下面是一个示例演示−
假设我们的输入是 −
The input matrix:
9 8 9 8
8 7 8 7
7 6 7 6
6 5 6 5
期望的输出结果将会是 −
The border elements of the matrix is:
9 8 9 8
8 7
7 6
6 5 6 5
步骤
Step 1 - START
Step 2 - Declare an integer matrix namely input_matrix, an object of the class BoundaryElements namely border_values.
Step 3 - Define the values.
Step 4 - Iterate over each element of the matrix using two for-loops and check if the element is a boundary element using Boolean OR condition.
Step 5 - Display the boundary elements.
Step 5 - Stop
示例1
在这里,输入是根据提示由用户输入的。
public class BoundaryElements {
public static void main(String[] args) {
int input_matrix[][] = new int[][] {
{ 9, 8, 9, 8 },
{ 8, 7, 8, 7 },
{ 7, 6, 7, 6 },
{ 6, 5, 6, 5 }
};
System.out.println("The matrix is defined as: ");
for (int x = 0; x < input_matrix.length; x++) {
for (int y = 0; y < input_matrix[x].length; y++) {
System.out.print(input_matrix[x][y] + " ");
}
System.out.println();
}
BoundaryElements border_values = new BoundaryElements();
System.out.println("The border elements of the matrix is:");
for (int x = 0; x < input_matrix.length; x++) {
for (int y = 0; y < input_matrix[x].length; y++) {
if (x == 0 || y == 0 || x == input_matrix.length - 1
|| y == input_matrix[x].length - 1) {
System.out.print(input_matrix[x][y] + " ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
输出
The matrix is defined as:
9 8 9 8
8 7 8 7
7 6 7 6
6 5 6 5
The border elements of the matrix is:
9 8 9 8
8 7
7 6
6 5 6 5
示例2
在这里,整数已经被先前定义并且它的值被访问并显示在控制台上。
public class BoundryElements {
public void Boundary_Elements(int input_matrix[][]) {
System.out.println("The matrix is defined as: ");
for (int x = 0; x < input_matrix.length; x++) {
for (int y = 0; y < input_matrix[x].length; y++) {
System.out.print(input_matrix[x][y] + " ");
}
System.out.println();
}
System.out.println("The border elements of the matrix is:");
for (int x = 0; x < input_matrix.length; x++) {
for (int y = 0; y < input_matrix[x].length; y++) {
if (x == 0 || y == 0 || x == input_matrix.length - 1
|| y == input_matrix[x].length - 1) {
System.out.print(input_matrix[x][y] + " ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
int input_matrix[][] = new int[][] {
{ 9, 8, 9, 8 },
{ 8, 7, 8, 7 },
{ 7, 6, 7, 6 },
{ 6, 5, 6, 5 }
};
BoundryElements border_values = new BoundryElements();
border_values.Boundary_Elements(input_matrix);
}
}
输出
The matrix is defined as:
9 8 9 8
8 7 8 7
7 6 7 6
6 5 6 5
The border elements of the matrix is:
9 8 9 8
8 7
7 6
6 5 6 5