编写一个Java程序,使用For循环和While循环打印空心盒数字模式,并附有示例。
Java 打印空心盒数字模式程序(使用 For 循环)
此Java程序允许用户输入行数和列数。接下来,它打印数字1组成的空心盒数字模式。我的意思是,它打印第一行、最后一行、第一列和最后一列为1,其余元素为空。
import java.util.Scanner;
public class HollowBoxNumber1 {
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(" ");
}
}
System.out.print("\n");
}
}
}

第一个For 循环用于从1迭代到总行数。接下来,我们使用嵌套 For 循环将j从1迭代到总列数。
用户输入值:行数 = 7,列数 = 9
第一个 For 循环 – 第一次迭代: for(i = 1; i <= 7; i++)
条件为真。因此,它进入第二个 For 循环
第二个 For 循环 – 第一次迭代: for(j = 1; 1 <= 9; 1++)
条件为真。因此,它检查 If 语句中的条件
if(i == 1 || i == rows || j == 1 || j == columns)
=> if(1 == 1 || 1 == 7 || 1 == 1 || 1 == 9) – 条件为真。因此,它将打印 1
对其余的Java迭代重复相同的操作。
使用 While 循环打印空心盒数字模式的程序
这个显示数字空心盒的Java程序与上面的示例相同,但我们使用的是While 循环。
import java.util.Scanner;
public class HollowBoxNumber2 {
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(" ");
}
j++;
}
i++;
System.out.print("\n");
}
}
}
使用 While 循环打印的空心盒数字模式输出
Please Enter Number of Rows : 9
Please Enter Number of Columns : 14
1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1
Java 打印空心盒数字模式示例 3
这个Java程序与第一个示例相同。但它打印第一行、最后一行、第一列和最后一列为0,其余元素为空格。
import java.util.Scanner;
public class HollowBoxNumber3 {
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(" ");
}
}
System.out.print("\n");
}
}
}
Please Enter Number of Rows : 10
Please Enter Number of Columns : 20
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
评论已关闭。