java内外循环打印阶梯*号

一.顺阶梯*打印

  先上结果图  

  思路:该结果图的基本组成单位是一个*号,采用内外for循环来实现,代码如下:

 1 class dayin 
 2 {
 3     public static void main(String[] args)
 4     {
 5         for(int x=4;x>=0;x--)
 6         {
 7             for(int y=5;(y-x)>0;y--)
 8             {
 9                 System.out.print("*");
10             }
11             System.out.println();
12         }
13     }
14 }

二.倒阶梯打印

  直接上代码1:

 1 class dayin 
 2 {
 3     public static void main(String[] args)
 4     {
 5         for(int x=0;x<5;x++)
 6         {
 7             for(int y=5;(y-x)>0;y--)
 8             {
 9                 System.out.print("*");
10             }
11             System.out.println();
12         }
13     }
14 }

  代码2:

 1 class dayin 
 2 {
 3     public static void main(String[] args)
 4     {
 5         for(int x=0;x<5;x++)
 6         {
 7             for(int y=x;y<5;y++)
 8             {
 9                 System.out.print("*");
10             }
11             System.out.println();
12         }
13     }
14 }

  

  通过在外循环里加入System.out.println(); 来实现跳行。

总结:会发现,外循环控制的是行数,内循环控制的是列数(个数),那么自然而然地,外循环只需让其循环5次即可,

关键的一点是在内循环的循环条件,调整行变量和列变量的关系以达目的,利用好便会游刃有余。

原文地址:https://www.cnblogs.com/gaigaichen/p/8258632.html