本文介绍了如何每行显示5个倍数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须显示一个表来检测2个数字的倍数。

I have to display a table for detecting multiples for 2 numbers.

我在格式化输出时遇到问题。

I'm having trouble formatting my output.

倍数应打印左对齐,每列8个字符,每行5个倍。

The multiples should be printed left-aligned in columns 8 characters wide, 5 multiples per line.

I知道它应该很简单,但我无法弄清楚如何每行显示5个倍数。

I know it should be simple but i cant figure out how to display 5 multiples per line.

任何人都可以帮忙吗?

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

299 297 275 273 264
260 253 247 242 234
231 221 220 209 208

推荐答案

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

You could print a new line every n amount of times and reset it to 0 using a col variable to keep track.

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;
   }
}

这篇关于如何每行显示5个倍数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 19:07