打印两行彼此格式化

我正在尝试格式化乘法表的输出,其中一行只能有 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 


绝地无双
浏览 193回答 3
3回答

炎炎设计

每 5 个数字打印一个换行符:calculation = number * i;System.out.printf("%-5s ", calculation);if (i % 5 == 0) {&nbsp; &nbsp;System.out.println();}&nbsp; &nbsp;&nbsp;

白猪掌柜的

我认为你有多种选择来实现这一点: 1. 在第 5 次迭代后打印一个新的空行 2. 添加"\n"到行尾标记1.for (int i = 1; i <= 10; i++ ) {&nbsp; &nbsp; &nbsp; &nbsp; calculation = number * i;&nbsp; &nbsp; &nbsp; &nbsp; if (i % 5 == 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; System.out.printf("%-5s ", calculation);}2.for (int i = 1; i <= 10; i++ ) {&nbsp; &nbsp; &nbsp; &nbsp; calculation = number * i;&nbsp; &nbsp; &nbsp; &nbsp; if (i % 5 == 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.printf("\n");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; System.out.printf("%-5s ", calculation);}希望这可以帮助

斯蒂芬大帝

打印 5 个元素后打印换行符:if(i % 5 == 0)&nbsp; &nbsp;System.out.println();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java