【问题标题】:Printing an array in a table format以表格格式打印数组
【发布时间】:2014-08-18 18:46:13
【问题描述】:

我有一个包含 50 个数字的数组,但不知道如何将数组输出到类似格式的表格中。

目前,当我打印我的数组时,它被输出为一长串数字,而我的目标是 10 行,每行包含 5 个数字。

此外,我希望每个值都是 3 位值。因此 1 将被表示为 001,以提高可读性和显示效果。

import java.util.*;
public class Random50 {
    public static void main (String[] args)
    {
        final int MAX_SIZE = 50;
        int[] r50 = new int[MAX_SIZE];

        Random rand = new Random();

        for (int i=0; i<r50.length; i++)
        {   
            r50[i] = rand.nextInt(1000);

            for (int j=0;j<i;j++)
            {               
                if (j!=i && r50[i] == r50[j])
                {
                    System.out.println("Duplicate: " + r50[i]);
                    r50[i] = rand.nextInt(1000);
                }

            }
        }

        System.out.printf(Arrays.toString(r50));

    }

}

【问题讨论】:

标签: java arrays printf output


【解决方案1】:

您确实应该在每个帖子中只问 1 个问题,所以我会回答您的第一个问题 - 这样其他用户可以在将来找到相关信息(不要刻薄)。

如果您想每隔五个数字在新行上开始打印,您可以使用modulus 运算符%

for(int i = 0; i < 50; i++){
    if(i % 5 == 0){ // True every fifth value
        System.out.print("\n"); // Print a new line
    }

    ... // Your other code goes here
}

【讨论】:

  • 您正在打印两个换行符 :)
  • 对不起,我是新来的!当我输入你给出的代码时,不是在每 5 个 [i] 值之后创建一个新行,而是先创建 5 个空行,然后仍然是我的 50 个数字的一​​行。
  • @freshwaterjoe 我帖子中的for loop 只是一个例子。您需要将我的回答中的if 声明放在您的for loop 中。我相信这对你来说是for (int i=0; i&lt;r50.length; i++)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-08
相关资源
最近更新 更多