有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用println按单位打印同一列中的数字列表?

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

为了美观,我需要我的价值观的单位在同一列中。。。所以当我编写代码时会出现这个问题:

一,

二,

三,

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

我的预期产出:

Expected Results


共 (4) 个答案

  1. # 1 楼答案

    如果你只是想达到你的间距,一个选择是使用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
    
  2. # 2 楼答案

    获取数组maxLength中最长字符串的大小,或者可以假设所有字符串的长度都不会超过给定的数字: int maxLength = 100 // as example

    然后用它像这样打印:System.out.printf("%" + maxLength + "s%n", treesOfForest[j]);

    public void display() {
    
            int j;
            int maxLength = 100; // 
            System.out.println(name);
            for (j = 0; j < treesOfForest.length; j++) {
                 if (treesOfForest[j] != null) {
                     System.out.printf("%" + maxLength + "s%n", treesOfForest[j]);
                 }
            }
    }
    
  3. # 3 楼答案

    您可以使用string来解决这个问题

    public class Main {
        public static void main(String[] args) {
                printList();
        }
    
        public static void printList() {
            int maxLen = 0;
            int arr[]={1, 2, 3, 10, 111, 0};
            for (int i=0 ; i<arr.length; i++) {
                int len = String.valueOf(arr[i]).length();
                if (maxLen < len) {
                    maxLen = len;       
                }   
            }
    
            for (int i=0 ; i<arr.length; i++) {
                int len = String.valueOf(arr[i]).length();
                int offset = maxLen - len;
                String spaces = "";
    
                for (int j=0; j<offset; j++) {
                    spaces += " ";
                }
                System.out.println(spaces + arr[i]);
            }
        }
    }
    
  4. # 4 楼答案

    你会像以前一样使用printf,但是,你需要包含一个最小宽度。在printf中,如果给定“%3d”,则说明任何插值数的最小宽度应为3列。也就是说,如果少于3位,则会留下空格。你也可以改变这种行为。例如,“%03d”,这将在pad中留下0而不是空格

    class Main {
      public static void main(String[] args) {
        int[] treesOfForest = {10,5,7,9,111};
        int j;
        for (j = 0; j < treesOfForest.length; j++) {
            System.out.printf("%3d : %3d\n", (j+1), treesOfForest[j]);
        }
      }
    }
    

    Test Code

    TL;DR使用System.out.printf("%<min-width>d", numberToPrint);确保最小宽度大于或等于任何数字中的最大数字

    有关printfvisit的更多信息