我需要打印出一个如下所示的三角形:
*
**
***
****
我现在的代码
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();
}
我明白了
*
**
***
****
*****
******
答案 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)
答案 4 :(得分:0)
只需在星号之前打印空格即可。