我需要帮助。我的任务是使用嵌套循环编写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中有更好的方法吗?
答案 0 :(得分:10)
通过使用Math.getExponent()
动态重复空格并格式化%3d
...
public static void f(int n) {
for (int i = 0; i < n; i++) {
for (int l = n - i; l > 0; l--) { // padding for symmetry
System.out.print(" ");
}
for (int j = 0; j <= i; j++) { // "left side" of pyramid
System.out.printf("%3d ", 1 << j);
}
for (int k = i - 1; k >= 0; k--) { // "right side" of pyramid
System.out.printf("%3d ", 1 << k);
}
System.out.println();
}
}
输出:
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
答案 1 :(得分:5)
您将使用带有控制输出的if语句的嵌套循环。
此代码可以帮助您进行格式化。你必须弄清楚如何添加||这样它就会翻转三角形,以及如何格式化你的打印语句,使它看起来像那样。
int totalWidth = 8;
for (int row = 1; row <= totalWidth; row++) {
for (int col = 1; col <= totalWidth; col++) {
if (col <= totalWidth - row) {
System.out.print(" ");
}else {
System.out.print("*");
}
}
System.out.println();
}
将输出
*
**
***
****
*****
******
*******
********
答案 2 :(得分:0)
public class pyramid
public static void f(int n) {
for (int i = 0; i < n; i++) {
for (int l = n - i; l > 0; l--) { // padding for symmetry
System.out.print(" ");
}
for (int j = 0; j <= i; j++) { // "left side" of pyramid
System.out.printf("%3d ", 1 << j);
}
for (int k = i - 1; k >= 0; k--) { // "right side" of pyramid
System.out.printf("%3d ", 1 << k);
}
System.out.println();
}
}