我正在做一个作业,在该作业中,我必须使用嵌套循环来编写位于其侧面的星号金字塔。该程序的输出应如下所示:
*
**
***
****
***
**
*
当我运行程序时,它仅显示代码的最后四行。我不知道为什么前三个没有出现。这是我的代码:
public class Main
{
public static void main(String[] args) {
for(int a = 0; a < 8; a++) //1
{
if(a < 4){
for(int b = a; b < 4; b++)
{
System.out.print("*");
}
}
if(a >= 4)
for(int c = a; c < 4; c++)
{
System.out.print("*");
}
System.out.println();
} //loop 1
}
}
这是我的输出:
****
***
**
*
((我的输出之后没有空白,这是由外部for循环迭代八次引起的。)如何使我的程序正确显示所有代码,而不仅仅是最后四行? ?
任何帮助将不胜感激。
您的逻辑中有几个错误:
rows
,所以第一个循环应迭代到a < 7
nested loop
应该从0
迭代到a
nested loop
应该从a
转到7
if-else
而不是两个if
语句这是我测试过的完整解决方案:
for(int a = 0; a < 7; a++) {
if(a < 4){
for(int b = 0; b <= a; b++)
System.out.print("*");
}else {
for(int c = a; c < 7; c++)
System.out.print("*");
}
System.out.println();
}
输出:
*
**
***
****
***
**
*
您接近。尝试这样的事情:
int size = 4;
for(int line = 1; line < size * 2; line++) {
if(line <= size) {
for(int i = 0; i < line; i++) {
System.out.print("*");
}
}
else {
for(int i = 0; i < size * 2 - line; i++) {
System.out.print("*");
}
}
System.out.println();
}