实心金字塔
拆解一下
打印从一开始每行递增2个*的金字塔,当要求行数为n时,有(规律1,3,5,7,9,11...)2*n - 1个*
打印空格,第一行空格数为n-1,第二行空格数为n-2,以此类推
使用for嵌套,有迭代量j,j在随着行数(i)增加空格数减少
在打印最后一个*换行
//打印金字塔
int tall = 7;
for(int i = 1; i <= tall; i++){
for(int j = tall;j > i; j--){
System.out.print(" ");
}
for(int asterisk = 1;asterisk <= (2*i) - 1;asterisk++ ){
System.out.print("*");
}
System.out.println();
}
空心金字塔
//打印金字塔
int tall = 10;
for(int high = 1; high <= tall; high++){
for(int column = high;column <= (tall -1); column++){//打印第一行的空格
System.out.print(" ");
}
if(high == 1 ){//打印第一行
for(int top = 1;top <= (2*high-1);top ++){
System.out.println("*");
}
}else if(high < tall){
System.out.print("*");//先打印起始*
for(int space = 1; space <= ((high-1)*2) -1 ;space ++){
//打印空格金字塔,打印中间部分的空格就是在打印一个金字塔,只不过比tall少两行
//打印第二行*开始打印空格,直到tall,所以要比打印实心金字塔少打一行
System.out.print(" ");
}
//打印另一个*
System.out.println("*");
}else{
//和打印第一行*分开是因为在如果和第一行在一起用的只能是不换行的
//导致打第二行没有换行,所以分开
int bottom = 1;
while(bottom <= (2*tall)-1 ){
System.out.print("*");
bottom++;
}
}
}