简体   繁体   中英

Print 3 arrays as a table in java

Print 3 arrays as a table in java

I am tried in different ways to print 3 arrays as a table. But I would like to know to do that correct way. Please help me.

These 3 are my arrays

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. This keeps like elements together.

Using the 2D String array, I created this output. 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.

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 . In the second instance, I input a 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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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