在java中打印对角线三角形

时间:2013-11-27 04:26:23

标签: java

我需要打印出一个如下所示的三角形:

*
 **
  ***
   ****

我现在的代码

    for(line = 0; line < size; line++){
        for(count = 0; count < line; count++){
            System.out.print("*");
            for(space = 0; space < line; space++)
                System.out.print(" ");
        }
            System.out.println();
    }

我明白了

* 
**  
***   
****    
*****     
******    

5 个答案:

答案 0 :(得分:2)

for(line = 0; line < size; line++){
    for(space = 0; space < line; ++space)
        System.out.print(" ");
    for(count = 0; count < line; count++)
        System.out.print("*");
    System.out.println();
}

答案 1 :(得分:0)

您正在同一行打印空格。在打印空格之前调用System.out.println();

编辑 - 示例:

for (line = 0; line < size; line++){
    for(space = 0; space < line - 1; space++)
        System.out.print(" ");
    for (count = 0; count < line; count++)
        System.out.print("*");
    System.out.println();
}

答案 2 :(得分:0)

您需要先打印前缀空格。然后打印星星。

试试这个:

    int line = 0;
    int size = 6;
    int count = 0;
    int space = 0;
    for (line = 0; line < size; line++) {
        //print spaces
        for (space = 0; space < line; space++)
            System.out.print(" ");

        //Print stars
        //Note: here count condition should be count < line+1, rather than count < line
        //If you do not do so, the first star with print as space only.
        for (count = 0; count < line+1; count++) {
            System.out.print("*");

        }
        System.out.println();
    }

控制台输出:

*
 **
  ***
   ****
    *****
     ******

答案 3 :(得分:0)

class Pyramid { public static void main(String args[]) { java.util.Scanner pyr=new java.util.Scanner(System.in); System.out.println("type a no. to make Pyramid"); int n= pyr.nextInt(); for (int i=1; i<=n; i++) { for(int j=n; j>i; j--) { System.out.print(" "); } for(int k=1; k<=i; k++) { System.out.print("* "); } System.out.println(); } }

答案 4 :(得分:0)

只需在星号之前打印空格即可。