首页 > 解决方案 > 如何使用 println 按单位打印同一列中的数字列表?

问题描述

我承认这是一个愚蠢的问题,但它只是我无法解决的大型计算项目的一小部分。为了打破它,我想在新行上打印我的数组值。

为了美观,我需要将我的值的单位放在同一列中......所以当我编码时会出现这种情况:

1

2

3

10

111

0

我的代码:

public void display() {

        int j;

            System.out.println(name);
            for (j = 0; j < treesOfForest.length; j++) {
                if (treesOfForest[j] != null) {
                    System.out.print(" ");
                    System.out.printf("%d",(j+1));
                    System.out.println( " :   " + treesOfForest[j]);
                }
            }
}

我的预期输出:

预期成绩

标签: javaarrays

解决方案


如果您只想实现间距,一种选择是使用String#format

int[] treesOfForest = new int[] {1, 2, 3, 10, 111, 0};
for (int j=0; j < treesOfForest.length; j++) {
    System.out.println(String.format("%3d", treesOfForest[j]));
}

  1
  2
  3
 10
111
  0

推荐阅读