簡體   English   中英

如何打印數組表?

[英]How to print a table of arrays?

我是來看看是否有人能夠幫助解決這個問題。

我正在嘗試打印一個看起來像這樣的表格

             Month #1      Month #2
   Person 1  $1293         $128
   Person 2  $122          $1233

我已經完成了獲取數字的所有其他步驟,等等,我只是停留在獲取正確輸出作為表格的最后一步。

int[][] table = new int[people][month];

     // Load the table with values
    for (int i=0; i < table.length; i++){     
          for (int j=0; j < table[i].length; j++){
            table[i][j] = r.nextInt(20000-1000) + 1000;
           }
      }

      // Print the table
      System.out.println("\n\nSummer Internship Salary Information:");
      for (int i=0; i < table.length; i++) {
          for (int j=0; j < table[i].length; j++)                    
             System.out.print ("Person #" + (i+1) + "$" + table[i][j] + "\t");
         System.out.println();     

      } 

數組的初始大小由用戶決定。 以及用值加載表格的第一部分。 那可以忽略。

我真正遇到麻煩的部分是從表格中打印出來。 從我現在擁有的代碼來看,它給出了一個輸出

     person#1 $12312   person #1 $12312
     person#2 $12312   person #2 $12312

(請注意,數字不是正確的數字,這只是一個示例)

我怎樣才能讓它有一個看起來像這樣的輸出:

              Month#1   Month#2
    Person#1  $12312    $12312
    Person#2  $12312    $12312

並且我不允許在本練習中使用 call 方法或 JCF。

假設所有人都有相同的月份數:

System.out.println("\n\nSummer Internship Salary Information:");
for (int j=0; j < table[0].length; j++) {
    System.out.print("\tMonth #" + (j+1));
}
for (int i=0; i < table.length; i++) {
    System.out.print("\nPerson #" + (i+1));
    for (int j=0; j < table[i].length; j++) {
        System.out.print("\t$" + table[i][j]);
    }
}
System.out.println();

請注意,Person# 已從內部循環中取出,並首先打印列標題。

還要注意,如果任何數字太寬(比制表位寬),它會破壞布局。 你必須更聰明地解決這個問題(首先找到每列的最大寬度或截斷值)

(編輯以將制表符和換行符放在更好的位置;更少的字符串且沒有尾隨制表符)

由於列的可變性質,我也會計算每列的“所需寬度”。 這將用於“填充”較短的列以確保列對齊...

這將允許在不需要任何額外補償的情況下增加人數和工資規模......

public class SalaryColumns {

    public static void main(String[] args) {

        int people = 20;
        int month = 12;

        String monthLabel = "Month #";
        String personLabel = "Person #";

        Random r = new Random(System.currentTimeMillis());
        int[][] table = new int[people][month];

        int[] columWidths = new int[month + 1];
        columWidths[0] = personLabel.length() + Integer.toString(people).length() + 1;
        // Load the table with values
        for (int i = 0; i < table.length; i++) {
            for (int j = 0; j < table[i].length; j++) {
                table[i][j] = r.nextInt(20000 - 1000) + 1000;
                columWidths[j + 1] = Math.max(
                        columWidths[j + 1], 
                        Math.max(
                            monthLabel.length() + Integer.toString(month).length() + 1, 
                            Integer.toString(table[i][j]).length() + 2));
            }
        }


        // Print the table
        System.out.println("\n\nSummer Internship Salary Information:");
        System.out.print(pad("", columWidths[0]));
        for (int i = 0; i < month; i++) {
            String value = monthLabel + String.format("%d", i);
            value += pad(value, columWidths[i + 1]);
            System.out.print(value);
        }
        System.out.println();

        for (int i = 0; i < table.length; i++) {
            String value = personLabel + String.format("%d", i);
            value += pad(value, columWidths[0]);
            System.out.print(value);
            for (int j = 0; j < table[i].length; j++) {
                value = String.format("$%d", table[i][j]);
                value += pad(value, columWidths[j + 1]);
                System.out.print(value);
            }
            System.out.println();

        }
    }

    public static String pad(String value, int length) {
        StringBuilder sb = new StringBuilder(length);
        while ((value.length() + sb.length()) < length) {
            sb.append(" ");
        }
        return sb.toString();
    }
}

輸出類似...

           Month #0  Month #1  Month #2  Month #3  Month #4  Month #5  Month #6  Month #7  Month #8  Month #9  Month #10 Month #11 
Person #0  $19428    $6333     $19057    $9502     $3265     $3731     $13855    $10254    $2997     $11370    $3264     $13038    
Person #1  $11988    $2313     $7722     $13457    $1100     $10589    $5453     $5996     $12301    $11490    $12283    $4407     
Person #2  $15179    $13993    $19421    $12370    $12090    $18623    $13716    $13215    $7308     $8446     $6657     $7861     
Person #3  $19673    $2956     $10505    $11141    $2020     $1025     $6833     $8821     $4366     $4127     $8938     $16353    
Person #4  $17210    $9442     $7960     $3178     $19924    $17406    $9637     $11655    $13862    $9136     $17205    $10832    
Person #5  $1609     $16141    $17245    $5073     $5716     $17390    $11861    $10235    $12540    $6037     $5199     $1782     
Person #6  $10721    $2257     $16660    $6635     $17384    $9606     $17578    $16799    $4066     $1960     $9563     $4705     
Person #7  $13224    $17277    $5932     $8532     $17321    $12650    $9672     $12527    $2251     $2702     $9033     $10322    
Person #8  $11625    $14107    $1171     $19300    $18455    $13178    $15637    $19687    $12751    $8870     $9412     $6501     
Person #9  $18550    $17017    $6902     $16676    $1057     $12067    $17656    $9220     $15494    $18450    $17341    $10378    
Person #10 $18408    $1907     $1203     $17781    $17106    $4861     $19259    $16245    $12223    $16278    $4429     $18283    
Person #11 $17548    $6160     $18262    $9116     $15075    $16619    $19431    $3463     $15789    $17814    $2059     $16414    
Person #12 $3882     $14816    $6580     $14257    $2192     $11033    $1387     $12269    $14246    $18406    $14794    $9036     
Person #13 $14124    $10216    $11960    $7462     $18001    $6254     $12928    $18118    $14161    $10585    $8102     $7295     
Person #14 $9849     $4085     $7184     $16173    $6847     $10288    $1796     $17384    $11323    $10811    $2636     $9946     
Person #15 $13500    $15157    $7618     $1810     $9368     $3295     $12586    $17489    $16092    $10978    $15227    $5506     
Person #16 $19668    $8540     $16249    $1039     $13672    $14082    $8978     $2710     $17092    $11280    $8090     $10266    
Person #17 $18138    $7467     $18246    $7110     $16501    $6583     $14026    $14204    $10877    $18628    $14575    $4836     
Person #18 $15090    $1579     $15613    $8480     $15854    $15687    $10024    $17004    $15452    $16351    $13714    $19755    
Person #19 $11015    $1152     $11733    $7620     $18217    $8518     $7243     $11819    $10313    $4339     $13532    $13700    

我知道這個帖子很老了,但是因為我經常陷入這個問題,可能是因為網上很多人都在看,所以我終於想發表我的答案了。

我寫了一個非常簡單的類,它使用String.format方法來格式化一個通用的對象表:

public class TableFormatter {
    private int columns;
    private List<String> cells = new LinkedList<>();
    private int minSpacesBetweenCells = 4;
    private boolean alignLeft = true;
    private int maxLength = 0;

    public TableFormatter(int columns) {
        this.columns = columns;
    }

    public TableFormatter insert(Object... cells) {
        for (Object content : cells) {
            String cell = content.toString();
            maxLength = Math.max(maxLength, cell.length());
            this.cells.add(cell);
        }
        return this;
    }

    public TableFormatter setMinSpacesBetweenCells(int minSpacesBetweenCells) {
        this.minSpacesBetweenCells = minSpacesBetweenCells;
        return this;
    }

    public TableFormatter alignCellsToRight() {
        this.alignLeft = false;
        return this;
    }

    public TableFormatter alignCellsToLeft() {
        this.alignLeft = true;
        return this;
    }

    @Override
    public String toString() {
        String format = "%";
        if (alignLeft)
            format += "-";
        format += maxLength + "s";

        String spaces = new String(new char[minSpacesBetweenCells]).replace("\0", " ");

        StringBuilder sb = new StringBuilder();

        int row = 0;
        int currentColumn = 0;
        for (String cell : cells) {
            if (currentColumn == 0) {
                if (row > 0)
                    sb.append("\n");
            } else {
                sb.append(spaces);
            }

            sb.append(String.format(format, cell));

            currentColumn = (currentColumn + 1) % columns;
            if (currentColumn == 0)
                row++;
        }

        return sb.toString();
    }

    public static void main(String[] args) {
        TableFormatter tableFormatter = new TableFormatter(3);

        tableFormatter.insert("column1", "column2", "column3");
        tableFormatter.insert("e11", 12, "e13");
        tableFormatter.insert("e21", "e22", 23);
        tableFormatter.insert(3.1d, "e32", "e33");
        tableFormatter.insert("e41", "e42", true);

        System.out.println(tableFormatter);
    }
}

請參閱類底部的主要方法。 它產生以下輸出:

column1    column2    column3
e11        12         e13    
e21        e22        23     
3.1        e32        e33    
e41        e42        true   

我希望這對這篇文章的下一個訪問者有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM