小白使用java循环语句打印空心棱形#初学者#
class Test{
public static void main(String []args){
int totalLevel = 15; //定义层数
for (int i = 1; i <= totalLevel; i++ ) {
if (i <= (totalLevel/2 + 1)) { //处理棱形上半截
for (int z = 1; z <= (totalLevel/2 + 1)-i ;z++ ) {
System.out.print(" "); //对应行数打印对应数量的空格
}
for (int j = 1; j <= 2*i - 1; j++ ) {
if (j == 1 || j == 2*i-1 ) {
System.out.print("*"); //对应地方输出※号
}else{
System.out.print(" "); //对应地方输出空格
}
}
System.out.println(" ");
}else{ //处理棱形下半截
for (int z1 = 1; z1 <= (2*i - totalLevel - 1)/2 ; z1++ ) {
System.out.print(" "); //对应行数打印对应数量的空格
}
for (int j1 = 1; j1 <= 2*(totalLevel-i)+1; j1++ ) {
if (j1 == 1 || j1 == 2*(totalLevel-i)+1) {
System.out.print("*"); //对应地方输出※号
}else{
System.out.print(" "); //对应地方输出空格
}
}
System.out.println(" "); //换行输出
}
}
}
}
输出结果:
程序存在缺陷:当层数为偶数时,输出图型就不正确,求大佬解惑