【发布时间】:2011-11-09 19:17:50
【问题描述】:
我需要帮助。我的任务是编写一个使用嵌套循环的 Java 程序来打印出以下输出模式:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
//pattern1
for(int outer=1;outer<=6;outer++) // outer loop controls number of rows
{
for(int inner=1;inner<=outer; inner++) // another loop to control number of numbers in each row.
{
System.out.print(inner);
}
System.out.println(); // move the cursor from the end of the current line to the beggiing to the next line
}
//pattern 2
for(int outer =1; outer<=6 ; outer++) //outer loop controls number of rows
{
//3-1 create spaces before numbers.
for(int space=1; space<=6-outer; space++ ) //group controls number of spaces
{
System.out.print(" ");
}
//3-2 print out real numbers.
for(int inner=1;inner<=outer; inner++) // another loop to control number of numbers in each row.
{
System.out.print(inner);
}
System.out.println();
}
这两个代码是背靠背的,但我不明白如何让数字2 4 8 16 等出现,并将它们背靠背。
我的代码有什么问题?在 Java 中有没有更好的方法来做到这一点?
【问题讨论】:
-
我喜欢它的保护方式,但有一个负面的投票数。