好吧,您已经解决了大多数问题,而您上次更新的版本已经正确打印了数字。
你还需要解决的唯一问题是格式化,使它看起来不错。
从您当前的代码开始,有两件事需要改变:
所有打印的数字都应该占用相同的空间(7)。您已经以这种方式格式化了“右侧”打印的数字,您所要做的就是对其他数字执行相同的操作。
你目前总是在线前添加8 * 7个空格,这当然是不正确的。如果你看金字塔,你可以清楚地看到第一行的8 * 7空格是正确的,但第二行需要前面7 * 7个空格,第三行需要6 * 7等。
这意味着为了获得金字塔的正确格式,你必须修改你的循环,打印空格,以便在主循环的每次迭代中运行1次。
这是一种如何更新代码以添加这两个更改的方法(我在更改后的行前面添加了注释作为说明):
public static void main (String[] args) throws java.lang.Exception
{
/** I added this counter to keep track
* of what iteration/line the loop currently is (see 2.)
*/
int iteration = 0;
for (int centerColumn = 1; centerColumn <= 128; centerColumn *=2){
/** Here we changed the loop condition
* from "j > 0" to "j > iteration"
* (So as iteration gets bigger, the loop runs less often)
*/
for (int j = 8; j > iteration; j--) {
System.out.printf("%7s", "");
}
for (int leftSide = 1; leftSide < centerColumn; leftSide*=2){
/** This should be self explanatory.
* You already did the same for rightSide.
* This will take care of 1.
*/
System.out.printf("%7d", leftSide );
}
for (int rightSide = centerColumn; rightSide > 0; rightSide/=2){
System.out.printf("%7d", rightSide);
}
/** Here we increment our counter with each iteration aka line that is printed */
iteration++;
System.out.println("");
}
}