【发布时间】:2017-02-02 17:54:13
【问题描述】:
我必须显示一个表格来检测 2 个数字的倍数。
我在格式化输出时遇到问题。
应在 8 个字符宽的列中左对齐打印倍数,每行 5 个倍数。
我知道它应该很简单,但我不知道如何每行显示 5 个倍数。
谁能帮忙?
public class Multiples_Loop_Table {
public static void main(String[] args)
{
int total = 0;
//table heading
System.out.println(" Integers from 300 to 200");
System.out.println(" -----------------------------");
for (int high = 300; high >= 200 && high <= 300; )
{
if ( (high % 11 == 0) != (high % 13 == 0))
{
System.out.printf("%-8d", high);
total += high;
}
high = high - 1;
}
//Total of all integers added togather
System.out.println("\nHere's the total for all integers: " + total );
//System.out.println("Here's the total number of integers found: " + );
//for every high add 1 to ?
示例:
299 297 275 273 264
260 253 247 242 234
231 221 220 209 208
【问题讨论】:
-
你应该给出一个期望输出的例子。
-
似乎您需要做的是使用一个变量,例如 cols(初始化为 0),然后在 printf() 行之后的 if 块中将其增加 1。但在 printf() 行之前,您对其进行测试以查看它是否等于 5。如果测试为真,则打印出换行符并将 cols 重置为 0。
-
@施平啊!对于那个很抱歉。固定的!你的建议很有帮助,我需要另一个变量。
标签: java formatting integer printf output