简体   繁体   English

在java中将3个数组打印为表格

[英]Print 3 arrays as a table in java

Print 3 arrays as a table in java在java中将3个数组打印为表格

I am tried in different ways to print 3 arrays as a table.我尝试以不同的方式将 3 个数组打印为表格。 But I would like to know to do that correct way.但我想知道以正确的方式做。 Please help me.请帮我。

These 3 are my arrays这 3 个是我的数组

Object[] arrayObjects = new GetDataFromDB().projectDB();
String[] arr_projectID = (String[])arrayObjects[0];
String[] arr_projectName = (String[])arrayObjects[1];
int[] arr_projectStatus = (int[])arrayObjects[2];

How can I print the table like this,我怎样才能像这样打印表格,

     -------- Project Table --------
| ProjectID | ProjectName | ProjectStatus |
|     01    |     p001    |       20      |
|     02    |     p002    |       70      |
|     03    |     p003    |       45      |
|     ..    |     ....    |       ..      |
|     ..    |     ....    |       ..      |

I tried as this way,我是这样试的

        String printPID ="";
        String printPName ="";
        String printPStatus ="";
        
        for (int i = 0; i < arr_projectID.length; i++) {
            
             pID = pID +"\n" + arr_projectID[i];
             printPID = "Project ID" + pID + "\n";
        } 
        
         for (int i = 0; i < arr_projectName.length; i++) {
            
             pName = pName + "\n" + arr_projectName[i];
             printPName = "Project name" + pName + "\n";
        } 
         
          for (int i = 0; i < arr_projectStatus.length; i++) {
            
             pStatus = pStatus + "\n" + arr_projectStatus[i];
             printPStatus = "Project Status" + pStatus + "\n";
        }

Your three separate arrays should be combined into one two dimensional String array.您应该将三个单独的数组组合成一个二维String数组。 This keeps like elements together.这使相似的元素保持在一起。

Using the 2D String array, I created this output.使用二维String数组,我创建了这个输出。 I used longer project names to illustrate how to calculate column widths to create a table.我使用更长的项目名称来说明如何计算列宽以创建表格。

              -------- Project Table --------               
| Project ID |        Project Name         | Project Status | 
|     01     |       Create Project        |       20       | 
|     02     |   Create PrintTable class   |       70       | 
|     03     |    Test PrintTable class    |       45       | 
|     04     | Write Stack Overflow Answer |       30       | 

When you're faced with a complex application, you divide the task into smaller tasks.当您面对复杂的应用程序时,您可以将任务划分为更小的任务。 You keep dividing until you can code each task.您一直在划分,直到您可以对每个任务进行编码。 One way to create a task list is to write pseudo-code.创建任务列表的一种方法是编写伪代码。

The pseudo-code I used to create this output goes like this:我用来创建这个输出的伪代码是这样的:

Define table name
Define field names
Initialize a 2D String array of projects
Create the output table
    Calculate the maximum size of each column
    Calculate the total width of the table
    Create the table header
    Create the header line
        Center each field title
    For each project
        Create a detail line
            Center each value
Print the output table.

I made extensive use of the StringBuilder class to create the output table.我广泛使用StringBuilder类来创建输出表。

I also used method overloading to create two methods that essentially do the same thing.我还使用方法重载来创建两个基本上做同样事情的方法。 Center some text.居中一些文本。 The reason that there are two methods is that in one instance, I input a StringBuilder .有两种方法的原因是,在一个实例中,我输入了一个StringBuilder In the second instance, I input a String .在第二个实例中,我输入了一个String

Here's the complete runnable example.这是完整的可运行示例。

public class PrintTable {

    public static void main(String[] args) {
        String tableName = "Project";
        String[] fieldNames = new String[] { "ID", "Name", "Status" };
        
        PrintTable printTable = new PrintTable();
        System.out.println(printTable.createTable(tableName, fieldNames));
    }
    
    private String[][] results;
    
    public PrintTable() {
        String[][] results = { { "01", "Create Project", "20" },
                { "02", "Create PrintTable class", "70" },
                { "03", "Test PrintTable class", "45" },
                { "04", "Write Stack Overflow Answer", "30" }
        };
        this.results = results;
    }
    
    public String createTable(String tableName, String[] fieldNames) {
        int[] maxWidth = calculateMaximumColumnWidth(tableName, fieldNames);
        int totalWidth = calculateTotalLineWidth(fieldNames, maxWidth);
        
        StringBuilder builder = createTable(tableName, fieldNames, 
                maxWidth, totalWidth);
        return builder.toString();
    }

    private int[] calculateMaximumColumnWidth(String tableName, 
            String[] fieldNames) {
        int[] maxWidth = new int[fieldNames.length];
        
        for (int i = 0; i < fieldNames.length; i++) {
            maxWidth[i] = tableName.length() + fieldNames[i].length() + 1;
        }
        
        for (int row = 0; row < results.length; row++) {
            for (int column = 0; column < results[row].length; column++) {
                maxWidth[column] = Math.max(maxWidth[column], 
                        results[row][column].length());
            }
        }
        
        return maxWidth;
    }

    private int calculateTotalLineWidth(String[] fieldNames, int[] maxWidth) {
        int totalWidth = fieldNames.length;
        for (int i = 0; i < fieldNames.length; i++) {
            totalWidth += maxWidth[i] + 2;
        }
        return totalWidth;
    }

    private StringBuilder createTable(String tableName, String[] fieldNames, 
            int[] maxWidth, int totalWidth) {
        StringBuilder builder = new StringBuilder();
        builder.append(createTitleLine(tableName, totalWidth));
        builder.append(System.lineSeparator());
        builder.append(createHeaderLine(tableName, fieldNames, maxWidth));
        builder.append(System.lineSeparator());
        builder.append(createDetailLines(maxWidth));
        return builder;
    }
    
    private StringBuilder createTitleLine(String tableName, int length) {
        StringBuilder builder = new StringBuilder();
        builder.append(createLine('-', 8));
        builder.append(" ");
        builder.append(tableName);
        builder.append(" Table ");
        builder.append(createLine('-', 8));
        return centerText(builder, length);
    }
    
    private StringBuilder createHeaderLine(String tableName, 
            String[] fieldNames, int[] maxWidth) {
        StringBuilder builder = new StringBuilder();
        builder.append("| ");
        for (int i = 0; i < fieldNames.length; i++) {
            StringBuilder text = new StringBuilder();
            text.append(tableName);
            text.append(" ");
            text.append(fieldNames[i]);
            builder.append(centerText(text, maxWidth[i]));
            builder.append(" | ");
        }
        return builder;
    }
    
    private StringBuilder createDetailLines(int[] maxWidth) {
        StringBuilder builder = new StringBuilder();
        
        for (int row = 0; row < results.length; row++) {
            builder.append("| ");
            for (int column = 0; column < results[row].length; column++) {
                builder.append(centerText(results[row][column], maxWidth[column]));
                builder.append(" | ");
            }
            builder.append(System.lineSeparator());
        }
        
        return builder;
    }
    
    private StringBuilder centerText(String text, int length) {
        StringBuilder builder = new StringBuilder(length);
        builder.append(text);
        return centerText(builder, length);
    }
    
    private StringBuilder centerText(StringBuilder text, int length) {
        if (text.length() >= length) {
            return text;
        }
        
        int spaces = (length - text.length()) / 2;
        text.insert(0, createLine(' ', spaces));
        return text.append(createLine(' ', length - text.length()));
    }
    
    private StringBuilder createLine(char c, int length) {
        StringBuilder builder = new StringBuilder(length);
        
        for (int i = 0; i < length; i++) {
            builder.append(c);
        }
        
        return builder;
    }

}
public class Foo {

    public static void main(String... args) throws IOException, InterruptedException {
        String[] ids = { "01", "02", "03" };
        String[] names = { "p001", "p002", "p003" };
        int[] statuses = { 20, 70, 45 };

        printTable(ids, names, statuses);
    }

    private static final String ID_COLUMN_NAME = "ProjectID";
    private static final String NAME_COLUMN_NAME = "ProjectName";
    private static final String STATUS_COLUMN_NAME = "ProjectStatus";

    public static void printTable(String[] ids, String[] names, int[] statuses) {
        int idColumnWidth = Math.max(ID_COLUMN_NAME.length() + 2, getMaxLength(ids));
        int nameColumnWidth = Math.max(NAME_COLUMN_NAME.length() + 2, getMaxLength(names));
        int statusColumnWidth = Math.max(STATUS_COLUMN_NAME.length() + 2, getMaxLength(statuses));
        int tableWidth = idColumnWidth + nameColumnWidth + statusColumnWidth + 4;

        System.out.println(middle("-------- Project Table --------", tableWidth));
        System.out.println('|' + middle(ID_COLUMN_NAME, idColumnWidth) +
                '|' + middle(NAME_COLUMN_NAME, nameColumnWidth) +
                '|' + middle(STATUS_COLUMN_NAME, statusColumnWidth) + '|');

        for (int i = 0; i < ids.length; i++)
            System.out.println('|' + middle(ids[i], idColumnWidth) +
                    '|' + middle(names[i], nameColumnWidth) +
                    '|' + middle(String.valueOf(statuses[i]), statusColumnWidth) + '|');
    }

    private static int getMaxLength(String[] arr) {
        return Arrays.stream(arr)
                     .mapToInt(String::length)
                     .max().orElse(0);
    }

    private static int getMaxLength(int[] arr) {
        return Arrays.stream(arr)
                     .mapToObj(String::valueOf)
                     .mapToInt(String::length)
                     .max().orElse(0);
    }

    private static String middle(String str, int columnWidth) {
        StringBuilder buf = new StringBuilder(columnWidth);
        int offs = (columnWidth - str.length()) / 2;

        for (int i = 0; i < offs; i++)
            buf.append(' ');

        buf.append(str);

        while (buf.length() < columnWidth)
            buf.append(' ');

        return buf.toString();
    }

}

Output:输出:

      -------- Project Table --------      
| ProjectID | ProjectName | ProjectStatus |
|    01     |    p001     |      20       |
|    02     |    p002     |      70       |
|    03     |    p003     |      45       |

table almost like your picture lol桌子几乎和你的照片一样,哈哈

package com.company;

import java.util.ArrayList;
import java.util.List;

public class Main {

    private String itemName;
    private double price;
    private int quantity;


    public Main(String itemName, double price, int quantity) {
        this.setItemName(itemName);
        this.setPrice(price);
        this.setQuantity(quantity);
    }


    public String getItemName() {
        return itemName;
    }

    public void setItemName(String itemName) {
        this.itemName = itemName;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }


    public static void printInvoiceHeader() {
        System.out.println(String.format("%30s %25s %10s %25s %10s", "Project ID", "|", "Project Name", "|", "Project Status"));
        System.out.println(String.format("%s", "----------------------------------------------------------------------------------------------------------------"));
    }

    public void printInvoice() {
        System.out.println(String.format("%30s %25s %10.2f %25s %10s", this.getItemName(), "| p", this.getPrice(), "|", this.getQuantity()));
    }

    public static List<Main> buildInvoice() {
        List<Main> itemList = new ArrayList<>();
        itemList.add(new Main("01", 1, 20));
        itemList.add(new Main("02", 2, 70));
        itemList.add(new Main("03", 3, 45));
        return itemList;
    }

    public static void main(String[] args) {

        Main.printInvoiceHeader();
        Main.buildInvoice().forEach(Main::printInvoice);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM