打印金字塔,记笔记的第一天

打印金字塔,记笔记的第一天,第1张

1.试着打印一个
*
**
***
****
*****
public class Yam{
     public static void main(String[] args){
      for(int a = 1;a<=5;a++){
           for(int b = 1;b<=a;b++){
                 System.out.print("*");
}
      System.out.println();//运行内层循环后,换行输出
}
}
}

2.试着打印以下金字塔
    *
   ***
  *****
 *******
*********
public class Yam{
     public static void main(String[] args){
     for(int a = 1;a<=5;a++){
         for(int c = 1;c<=5-a;c++){//第一行是4个空格,也就是说当前行空格数为总层数-当前层数
            System.out.print(" ");
}
          for(int b = 1;b<=a*2-1;b++){//每一层的星星是当前层数*2-1个
                System.out.print("*");
}
      System.out.println();
}
}
}

3.打印如下一个空心金字塔
    *
   * *
  *   *
 *     *
*********
public class Yam{
     public static void main(String[] args){
        for(int a =1;a<=5;a++){
        for(int c = 1;c<=5-a;c++){
            System.out.print(" ");
}
          for(int b = 1;b<=a*2-1;b++){
              if(b==1 || b==a*2-1 || a==5){//当b==1时此时输出第一个星星,而b==a*2-1时,输出的最后一个星星,当a==5,说明此时处在第五层,会输出全部的星星
               System.out.print("*");
}else{
               System.out.print(" ");
}
}
   System.out.println();
}
}
}

跟着韩老师学Java,忘了是第几天了,现在才开始记笔记。。。。。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/3002750.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-09-27
下一篇 2022-09-27

发表评论

登录后才能评论

评论列表(0条)

保存