我很难获得所需的输出。我知道已经发布了一些与我类似的问题,但我发现如果不进行大规模的检修,很难将我的代码与他们的解决方案联系起来。
我课堂作业的解决方案:
应该持续到金字塔的每个方向都等于1我的第二个方法"空格"是多余的,我不知道为什么。如有任何帮助,我们将不胜感激。
Blockq
public static void main(String[] args) {
numPar();
spaces();
}
private static void spaces() {
int x = 0;
if(x > 0 && x < 10) {
System.out.print(" ");
} else if (x > 10 && x < 99) {
System.out.print(" ");
} else if (x > 99) {
System.out.print(" ");
}
}
private static void numPar() {
int spaces = 14;
for(int i = 0; i<= 7; i++) {
for(int u = 0; u<spaces; u++) {
System.out.print(" ");
}
spaces--;
spaces--;
for(int j = 0 ; j <i ; j++) {
System.out.print(""+ (int) Math.pow(2,j)+" ");
}
for(int k = i ; k >=0 ; k--) {
System.out.print(""+ (int) Math.pow(2,k)+" ");
}
System.out.println("");
}
}
}
我使用String.format("%3s", (int) Math.pow(2, j))
使每个数字占据3位。您可以将此处的数字3
替换为要打印的最大数字的长度,从而使其具有动态性。我还更改了打印报表中的空格数。以下是打印均匀间隔金字塔的完整代码:-
public static void main(String[] args) {
numPar();
spaces();
}
private static void spaces() {
int x = 0;
if (x > 0 && x < 10) {
System.out.print(" ");
} else if (x > 10 && x < 99) {
System.out.print(" ");
} else if (x > 99) {
System.out.print(" ");
}
}
private static void numPar() {
int spaces = 14;
for (int i = 0; i <= 7; i++) {
for (int u = 0; u < spaces; u++) {
System.out.print(" ");
}
spaces--;
spaces--;
for (int j = 0; j < i; j++) {
System.out.print("" + String.format("%3s", (int) Math.pow(2, j)) + " ");
}
for (int k = i; k >= 0; k--) {
System.out.print("" + String.format("%3s", (int) Math.pow(2, k)) + " ");
}
System.out.println("");
}
}
String.format
解释:-String.format("%3s", str)
将打印字符串str
,并用空格填充,以使总长度小于3时为3。注意,你可以写任何东西而不是3——我用了3,因为你最大的数字长度是3。
因此,"A"将被打印为"__A"(2个空格(,而"Ab"将打印为"_Ab"(1个空格(。
我刚刚用你的Math.pow(2, j)
替换了str
。