java循环嵌套三角形_三角形左侧的java嵌套循环逻辑

好吧,您已经解决了大多数问题,而您上次更新的版本已经正确打印了数字。

你还需要解决的唯一问题是格式化,使它看起来不错。

从您当前的代码开始,有两件事需要改变:

所有打印的数字都应该占用相同的空间(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("");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值