如何在前端接触的情况下打印2个三角形?

时间:2015-03-05 02:18:15

标签: java for-loop

我正在尝试制作一个看起来像

的三角形
*                 *
**               **
***             ***
****           ****
*****         *****
******       ******
*******     *******
********   ********
*******************

我有代码执行此操作,但我不确定我的方法是否是正确的方法,因为我不能使用小于4的值作为我的 n 参数。

 public static void triangle(int n){   
    int shift = n*2 + 2;

    for(int row = 0; row <= n; row++ ){
        for(int j = 0; j <= (n*2)+(n/2); j++ ){
            if(j == 0 || j==shift){
                for(int i = 0; i <= row; i++){ 
                    System.out.print("*");
                    if(row == n && i == n)
                        System.out.print("*");

                }
            }

            if(row != n)
                System.out.print(' ');

        }
        shift-=2;
        System.out.println();
    }
}  

1 个答案:

答案 0 :(得分:1)

这是解决方案。

public static void triangle(int n){ 
    int shift = n*2;
    for(int row = 1; row <= n; row++ ){
        for(int j = 0; j < row; j++ )
            System.out.print("*");
        shift-=2;
        for(int k = 0 ; k<shift; k++)
            System.out.print(" ");

        for(int j = 0; j < row; j++ )
            System.out.print("*");    
        System.out.println();
            }


    }