zoukankan      html  css  js  c++  java
  • java实现打印正三角,倒三角

    正三角代码:

     1 package BasicType;
     2 /**
     3  * 封装一个可以根据用户传入值来打印正三角的方法
     4  * @author Administrator
     5  */
     6 
     7 public class Enme {
     8     //n代表打印的层数
     9     public static void print_positive_triangle(int n){
    10         //第一层1个,第二层三个,第三层5个...类比退出第n层就是last个*
    11         int last = 2*(n-1)+1;
    12         //控制打印多少层
    13         for (int i=0;i<n;i++)
    14         {   //计算出每一层左边要填充空格的个数
    15             int full_left = last/2-i;
    16             //打印完一层后需要换行
    17             System.out.println("");
    18             //控制本层要打印的样式,默认打印出正方形
    19             for(int j=0;j<=last;j++){
    20                 //如果j比要填充的空格数量少或者相等或j大于填充的*所占用的位置数与空格填充的位置数之和,就打印空格
    21                 if (j<=full_left||j>full_left+2*i+1){
    22                     System.out.print(" ");
    23                 }
    24                 else{
    25                 System.out.print("*");
    26                 }
    27             }
    28         }
    29         }
    30 
    31 public static void main(String[] args) {
    32     print_positive_triangle(5);    
    33 }
    34 }

     倒三角代码:

     1 public class Enme {
     2     
     3     //打印倒三角
     4     public static void print_nagative_triangle(int n){
     5         //最多*的那一层*的个数
     6         int last = 2*n-1;
     7         //控制打印多少层
     8         for (int i=n-1;i>=0;i--)
     9         {   //计算出每一层左边要填充空格的个数
    10             int full_left = n-i-1;
    11             System.out.println("");
    12             for(int j=0;j<last;j++){
    13                 if (j<full_left||j>=full_left+2*i+1){
    14                     System.out.print(" ");
    15                 }
    16                 else{
    17                 System.out.print("*");
    18                 }
    19             }
    20         }
    21 }
    22     
    23 public static void main(String[] args) {
    24 //    print_positive_triangle(5);    
    25     print_nagative_triangle(5);
    26 }
    27 }
  • 相关阅读:
    jquery append、prepend、before等等
    js模板引擎之juicer,特别好用
    js模板引擎之artTemplate
    smarty中调用php内置函数
    Win10安装软件时出现2502、2503错误代码的问题
    Nexus私有仓库简介
    【Maven】Nexus(Maven仓库私服)下载与安装
    [Nginx] – 性能优化 – 配置文件优化
    [Nginx] – 安全优化 – 配置文件优化
    VMware Authorization Service 未运行怎么解决
  • 原文地址:https://www.cnblogs.com/g177w/p/8365373.html
Copyright © 2011-2022 走看看