编写一个 Java 程序,使用 for 循环打印一个简单的数字图案。
import java.util.Scanner;
public class SimpleNumber1 {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
System.out.print("Simple Number Pattern Rows = ");
int rows = sc.nextInt();
System.out.println("Printing Simple Number Pattern");
for (int i = 1 ; i <= rows; i++ )
{
for (int j = 1 ; j <= i; j++ )
{
System.out.print(j + " ");
}
System.out.println();
}
}
}

这个示例使用 while 循环显示数字的直角三角形图案。
import java.util.Scanner;
public class SimpleNumber2 {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
int i = 1, j ;
System.out.print("Enter Rows = ");
int rows = sc.nextInt();
while (i <= rows)
{
j = 1 ;
while ( j <= i)
{
System.out.print(j + " ");
j++;
}
System.out.println();
i++;
}
}
}
Enter Rows = 9
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
此程序有助于使用 do while 循环打印简单的数字图案。
import java.util.Scanner;
public class SimpleNumber3 {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
System.out.print("Enter Rows = ");
int rows = sc.nextInt();
int i = 1, j ;
do
{
j = 1 ;
do
{
System.out.print(j + " ");
} while ( ++j <= i);
System.out.println();
} while (++i <= rows);
}
}
Enter Rows = 14
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10 11
1 2 3 4 5 6 7 8 9 10 11 12
1 2 3 4 5 6 7 8 9 10 11 12 13
1 2 3 4 5 6 7 8 9 10 11 12 13 14