为了账号安全,请及时绑定邮箱和手机立即绑定

打印两行彼此格式化

打印两行彼此格式化

绝地无双 2021-10-13 16:50:44
我正在尝试格式化乘法表的输出,其中一行只能有 5 个数字/整数。我正在 for 循环中使用 printf 方法尝试此操作,但到目前为止还没有工作。代码:System.out.println("Which multiplication table do you want to print?: ");int number = input.nextInt();int calculation;System.out.println("Multiplication table: " + number + ":");for (int i = 1; i <= 10; i++ ) {    calculation = number * i;    System.out.printf("%-5s ", calculation);}我的输出:3    6    9    12   15   18   21   24   27   30  我试图得到的输出: 3    6    9    12   15 18   21   24   27   30 
查看完整描述

3 回答

?
炎炎设计

TA贡献1808条经验 获得超4个赞

每 5 个数字打印一个换行符:


calculation = number * i;

System.out.printf("%-5s ", calculation);

if (i % 5 == 0) {

   System.out.println();

}    


查看完整回答
反对 回复 2021-10-13
?
白猪掌柜的

TA贡献1893条经验 获得超10个赞

我认为你有多种选择来实现这一点: 1. 在第 5 次迭代后打印一个新的空行 2. 添加"\n"到行尾标记


1.


for (int i = 1; i <= 10; i++ ) {

        calculation = number * i;

        if (i % 5 == 0) {

         System.out.println();

        }    

        System.out.printf("%-5s ", calculation);

}

2.


for (int i = 1; i <= 10; i++ ) {

        calculation = number * i;

        if (i % 5 == 0) {

         System.out.printf("\n");

        }    

        System.out.printf("%-5s ", calculation);

}

希望这可以帮助


查看完整回答
反对 回复 2021-10-13
?
斯蒂芬大帝

TA贡献1827条经验 获得超8个赞

打印 5 个元素后打印换行符:


if(i % 5 == 0)

   System.out.println();


查看完整回答
反对 回复 2021-10-13
  • 3 回答
  • 0 关注
  • 192 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号