编写一个 Java 程序,使用 For 循环和 While 循环打印 1 和 0 的方框数字模式,并附带示例。
Java 打印 1 和 0 的方框数字模式的 For 循环程序
此 Java 程序 允许用户输入行数和列数。接下来,它会打印 1 和 0 的方框数字模式。也就是说,它将第一行、最后一行、第一列和最后一列打印为 1,其余元素打印为 0。
// Java Program to Print Box Number Pattern of 1 and 0
import java.util.Scanner;
public class BoxNumber1 {
private static Scanner sc;
public static void main(String[] args)
{
int rows, columns, i, j;
sc = new Scanner(System.in);
System.out.print(" Please Enter Number of Rows : ");
rows = sc.nextInt();
System.out.print(" Please Enter Number of Columns : ");
columns = sc.nextInt();
for(i = 1; i <= rows; i++)
{
for(j = 1; j <= columns; j++)
{
if(i == 1 || i == rows || j == 1 || j == columns)
{
System.out.print("1");
}
else
{
System.out.print("0");
}
}
System.out.print("\n");
}
}
}

首先使用For 循环从 1 迭代到总行数。接下来,我们使用嵌套 For 循环将 j 从 1 迭代到总列数。
用户输入的数值:行数 = 10,列数 = 15
第一个 For 循环 – 第一次迭代: for(i = 1; i <= 10; i++)
条件为真。因此,它进入第二个 For 循环
第二个 For 循环 – 第一次迭代: for(j = 1; 1 <= 15; 1++)
条件为真。因此,它会检查 If 语句中的条件
if(i == 1 || i == rows || j == 1 || j == columns)
=> if(1 == 1 || 1 == 10 || 1 == 1 || 1 == 15) – 条件为真,因此打印 1
重复执行相同的操作以完成剩余的Java迭代。
Java 使用 While 循环打印 1 和 0 的方框数字模式程序
此 程序 与上面的示例相同。但在本 Java 程序中,我们使用While 循环来显示 1 和 0 的方框数字模式。
// Java Program to Print Box Number Pattern of 1 and 0
import java.util.Scanner;
public class BoxNumber2 {
private static Scanner sc;
public static void main(String[] args)
{
int rows, columns, i = 1, j;
sc = new Scanner(System.in);
System.out.print(" Please Enter Number of Rows : ");
rows = sc.nextInt();
System.out.print(" Please Enter Number of Columns : ");
columns = sc.nextInt();
while(i <= rows)
{
j = 1;
while(j <= columns)
{
if(i == 1 || i == rows || j == 1 || j == columns)
{
System.out.print("1 ");
}
else
{
System.out.print("0 ");
}
j++;
}
i++;
System.out.print("\n");
}
}
}
Please Enter Number of Rows : 7
Please Enter Number of Columns : 9
1 1 1 1 1 1 1 1 1
1 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 1
1 1 1 1 1 1 1 1 1
打印 0 和 1 的方框数字模式的程序 示例 3
此Java 程序与第一个示例相同。但此 Java 程序将第一行、最后一行、第一列和最后一列打印为 0,其余元素打印为 1。
// Java Program to Print Box Number Pattern of 0 and 1
import java.util.Scanner;
public class BoxNumber3 {
private static Scanner sc;
public static void main(String[] args)
{
int rows, columns, i, j;
sc = new Scanner(System.in);
System.out.print(" Please Enter Number of Rows : ");
rows = sc.nextInt();
System.out.print(" Please Enter Number of Columns : ");
columns = sc.nextInt();
for(i = 1; i <= rows; i++)
{
for(j = 1; j <= columns; j++)
{
if(i == 1 || i == rows || j == 1 || j == columns)
{
System.out.print("0 ");
}
else
{
System.out.print("1 ");
}
}
System.out.print("\n");
}
}
}
Please Enter Number of Rows : 8
Please Enter Number of Columns : 14
0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 1 1 1 1 1 1 0
0 1 1 1 1 1 1 1 1 1 1 1 1 0
0 1 1 1 1 1 1 1 1 1 1 1 1 0
0 1 1 1 1 1 1 1 1 1 1 1 1 0
0 1 1 1 1 1 1 1 1 1 1 1 1 0
0 1 1 1 1 1 1 1 1 1 1 1 1 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0