如何使用Java生成星形三角形图案

时间:2015-03-19 14:56:53

标签: java

如何使用java打印星形三角形图案。模式是这样的

            * ====> row 1
           * *
          *   *
         *     *
        * * * * *

它可以是n行,从第二行开始,在2个星之间有奇数个空格,例如1,3,5,最后一行的所有星都用一个空格分隔。

下面是我正在编写的打印三角形的代码?

public class Triangle
 {
public static void main(String[] args)
{
    int row = 4;
    int space =0;
    System.out.println("*");
    for (int i=1;i<row;i++)
    {
        System.out.print("*");
        for(space=0;space<i;space = space+i)
        {
            System.out.print(" ");
        }
        System.out.print("*");
    System.out.println();
    }


enter code here
    for(int i=0;i<=4;i++)
    {
        System.out.print("* ");
    }
}

}

我该如何处理?

2 个答案:

答案 0 :(得分:0)

public class Triangle {

    public static void DrawWithStars(int dimension)
    {
        if(dimension < 0)
        {
            //Assuming that a triangle with dimension = 0 is a dot....
            System.out.println("No valid dimension");
        }
        else
        {
            //To print the first dimension - 1 rows
            for (int i = 0; i < dimension; i++) 
            {
                for (int j = 0; j < dimension - i; j++) {
                    System.out.print(" ");
                }

                //Print the dot of the row 1 at the end
                if(i != 0)
                    System.out.print("*");

                for (int j = 0; j < 2 * i - 1; j++) {
                    System.out.print(" ");
                }

                System.out.println("*");
            }

            //To print the last row

            for (int i = 0; i < dimension; i++)
            {
                System.out.print("* ");
            }

            System.out.println("*");
        }
    }
}

答案 1 :(得分:0)

package apple;

public class Triangle
{
public static void main(String...strings){
    int midspace = -1;
    int row = 4;
    String star = "";
    for(int y=row-1; y>0; y--){ 
        for(int space = 1;space <= y ; space++){
            System.out.print(" ");
        }
        System.out.print("*");

        for(int i = midspace; i>0; i--)
            System.out.print(" ");
        midspace += 2;

        star = (y!=row-1) ? "*":"";
        System.out.println(star);

    }


    for(int y=((row*2)-1); y>0; y--){
        System.out.print("*");
    }
}

}