Java for 循环嵌套例子
1. for 嵌套打印数字
public class Welcome { public static void main(String[] args) { for(int i=1; i<10; i++) { for(int j=1; j<=i; j++) { System.out.print(j + " "); } System.out.println(); } } }
打印结果:
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
2. for嵌套打印
public class daxing { public static void main(String[] args) { for (int i = 0; i < 5; i++) { for (int j = i; j < 5; j++) { System.out.print("*"); } System.out.println(); } } }
打印结果:
*****
****
***
**
*
3. for循环嵌套,打印菱形
public class t8 { public static void main(String[] args) { //上半部分 for (int m = 1; m <= 10; m++) { //输出空格 for (int n = 9; n >= m ;n--) { System.out.print(" "); } //输出* 左上 for (int n = 1; n <= m; n++) { System.out.print("*"); } //右上 for (int n = 1; n < m; n++) { System.out.print("*"); } System.out.println(); } //下半部分 for (int m = 1; m <= 9; m++) { //输出空格 for (int n = 1; n <= m ;n++) { System.out.print(" "); } //输出* 左下 for (int n = 9; n >= m; n--) { System.out.print("*"); } //右下 for (int n = 9; n > m; n--) { System.out.print("*"); } System.out.println(); } } }
运行结果:
版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。