如何每行显示5个倍数?

时间:2017-02-02 17:54:13

标签: java formatting integer printf output

我必须显示一个表格,用于检测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

1 个答案:

答案 0 :(得分:0)

您可以每n次打印一个新行,并使用col变量将其重置为0以保持跟踪。

public static void main(String[] args) {

   int total = 0;
   int col   = 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)) {

           if (col == 5) {
               System.out.println();
               col = 0;
           }

           System.out.printf("%-8d", high);
           total += high;
           col++;
       }
       high = high - 1;
   }
}