以Java中的表格形式打印3个数组。

huangapple go评论80阅读模式
英文:

Print 3 arrays as a table in java

问题

// Print 3 arrays as a table in java

// 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];

// Print the table
System.out.println("-------- Project Table --------");
System.out.println("| ProjectID | ProjectName | ProjectStatus |");

for (int i = 0; i < arr_projectID.length; i++) {
    System.out.printf("|    %-6s |    %-8s |      %-8s |\n", arr_projectID[i], arr_projectName[i], arr_projectStatus[i]);
}

System.out.println("|     ..    |     ....    |       ..      |");
System.out.println("|     ..    |     ....    |       ..      |");
// I tried as this way,

StringBuilder printPID = new StringBuilder();
StringBuilder printPName = new StringBuilder();
StringBuilder printPStatus = new StringBuilder();

for (int i = 0; i < arr_projectID.length; i++) {
    printPID.append("\n").append(arr_projectID[i]);
}

for (int i = 0; i < arr_projectName.length; i++) {
    printPName.append("\n").append(arr_projectName[i]);
}

for (int i = 0; i < arr_projectStatus.length; i++) {
    printPStatus.append("\n").append(arr_projectStatus[i]);
}
英文:

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 =&quot;&quot;;
        String printPName =&quot;&quot;;
        String printPStatus =&quot;&quot;;
        
        for (int i = 0; i &lt; arr_projectID.length; i++) {
            
             pID = pID +&quot;\n&quot; + arr_projectID[i];
             printPID = &quot;Project ID&quot; + pID + &quot;\n&quot;;
        } 
        
         for (int i = 0; i &lt; arr_projectName.length; i++) {
            
             pName = pName + &quot;\n&quot; + arr_projectName[i];
             printPName = &quot;Project name&quot; + pName + &quot;\n&quot;;
        } 
         
          for (int i = 0; i &lt; arr_projectStatus.length; i++) {
            
             pStatus = pStatus + &quot;\n&quot; + arr_projectStatus[i];
             printPStatus = &quot;Project Status&quot; + pStatus + &quot;\n&quot;;
        }

答案1

得分: 3

你的三个分离的数组应该合并成一个二维的 String 数组。这样可以将相似的元素放在一起。

使用这个二维的 String 数组,我创建了以下的输出。我使用了较长的项目名称来说明如何计算列宽以创建一个表格。

              -------- 项目表 --------               
| 项目ID |        项目名称         | 项目状态 | 
|   01   |       创建项目         |    20    | 
|   02   |   创建 PrintTable 类   |    70    | 
|   03   |    测试 PrintTable 类  |    45    | 
|   04   | 写 Stack Overflow 回答 |    30    | 

当面对一个复杂的应用时,你会将任务分解为更小的任务。你不断分解,直到可以编码完成每个任务。创建任务列表的一种方法是编写伪代码。

我用来创建这个输出的伪代码如下:

定义表名
定义字段名
初始化一个项目的二维 String 数组
创建输出表格
    计算每列的最大宽度
    计算表格的总宽度
    创建表头
    创建头线
        居中每个字段标题
    对于每个项目
        创建细节行
            居中每个值
打印输出表格。

我广泛地使用了 StringBuilder 类来创建输出表格。

我还使用方法重载来创建了两个本质上做相同事情的方法。居中一些文本。之所以有两个方法,是因为在一个情况下,我输入了一个 StringBuilder,在第二个情况下,我输入了一个 String

这是完整可运行的示例。

public class PrintTable {
    
    public static void main(String[] args) {
        String tableName = "项目";
        String[] fieldNames = new String[] { "ID", "名称", "状态" };
        
        PrintTable printTable = new PrintTable();
        System.out.println(printTable.createTable(tableName, fieldNames));
    }
    
    private String[][] results;
    
    public PrintTable() {
        String[][] results = { 
            { "01", "创建项目", "20" },
            { "02", "创建 PrintTable 类", "70" },
            { "03", "测试 PrintTable 类", "45" },
            { "04", "写 Stack Overflow 回答", "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();
    }

    // ...(以下部分省略,因为这部分是具体的代码实现)
}
英文:

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 = &quot;Project&quot;;
		String[] fieldNames = new String[] { &quot;ID&quot;, &quot;Name&quot;, &quot;Status&quot; };
		
		PrintTable printTable = new PrintTable();
		System.out.println(printTable.createTable(tableName, fieldNames));
	}
	
	private String[][] results;
	
	public PrintTable() {
		String[][] results = { { &quot;01&quot;, &quot;Create Project&quot;, &quot;20&quot; },
				{ &quot;02&quot;, &quot;Create PrintTable class&quot;, &quot;70&quot; },
				{ &quot;03&quot;, &quot;Test PrintTable class&quot;, &quot;45&quot; },
				{ &quot;04&quot;, &quot;Write Stack Overflow Answer&quot;, &quot;30&quot; }
		};
		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 &lt; fieldNames.length; i++) {
			maxWidth[i] = tableName.length() + fieldNames[i].length() + 1;
		}
		
		for (int row = 0; row &lt; results.length; row++) {
			for (int column = 0; column &lt; 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 &lt; 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(&#39;-&#39;, 8));
		builder.append(&quot; &quot;);
		builder.append(tableName);
		builder.append(&quot; Table &quot;);
		builder.append(createLine(&#39;-&#39;, 8));
		return centerText(builder, length);
	}
	
	private StringBuilder createHeaderLine(String tableName, 
			String[] fieldNames, int[] maxWidth) {
		StringBuilder builder = new StringBuilder();
		builder.append(&quot;| &quot;);
		for (int i = 0; i &lt; fieldNames.length; i++) {
			StringBuilder text = new StringBuilder();
			text.append(tableName);
			text.append(&quot; &quot;);
			text.append(fieldNames[i]);
			builder.append(centerText(text, maxWidth[i]));
			builder.append(&quot; | &quot;);
		}
		return builder;
	}
	
	private StringBuilder createDetailLines(int[] maxWidth) {
		StringBuilder builder = new StringBuilder();
		
		for (int row = 0; row &lt; results.length; row++) {
			builder.append(&quot;| &quot;);
			for (int column = 0; column &lt; results[row].length; column++) {
				builder.append(centerText(results[row][column], maxWidth[column]));
				builder.append(&quot; | &quot;);
			}
			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() &gt;= length) {
			return text;
		}
		
		int spaces = (length - text.length()) / 2;
		text.insert(0, createLine(&#39; &#39;, spaces));
		return text.append(createLine(&#39; &#39;, length - text.length()));
	}
	
	private StringBuilder createLine(char c, int length) {
		StringBuilder builder = new StringBuilder(length);
		
		for (int i = 0; i &lt; length; i++) {
			builder.append(c);
		}
		
		return builder;
	}

}

答案2

得分: 1

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

}
英文:
public class Foo {
public static void main(String... args) throws IOException, InterruptedException {
String[] ids = { &quot;01&quot;, &quot;02&quot;, &quot;03&quot; };
String[] names = { &quot;p001&quot;, &quot;p002&quot;, &quot;p003&quot; };
int[] statuses = { 20, 70, 45 };
printTable(ids, names, statuses);
}
private static final String ID_COLUMN_NAME = &quot;ProjectID&quot;;
private static final String NAME_COLUMN_NAME = &quot;ProjectName&quot;;
private static final String STATUS_COLUMN_NAME = &quot;ProjectStatus&quot;;
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(&quot;-------- Project Table --------&quot;, tableWidth));
System.out.println(&#39;|&#39; + middle(ID_COLUMN_NAME, idColumnWidth) +
&#39;|&#39; + middle(NAME_COLUMN_NAME, nameColumnWidth) +
&#39;|&#39; + middle(STATUS_COLUMN_NAME, statusColumnWidth) + &#39;|&#39;);
for (int i = 0; i &lt; ids.length; i++)
System.out.println(&#39;|&#39; + middle(ids[i], idColumnWidth) +
&#39;|&#39; + middle(names[i], nameColumnWidth) +
&#39;|&#39; + middle(String.valueOf(statuses[i]), statusColumnWidth) + &#39;|&#39;);
}
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 &lt; offs; i++)
buf.append(&#39; &#39;);
buf.append(str);
while (buf.length() &lt; columnWidth)
buf.append(&#39; &#39;);
return buf.toString();
}
}

Output:

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

答案3

得分: 0

表格几乎像你的图片哈哈

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);
    }
}
英文:

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(&quot;%30s %25s %10s %25s %10s&quot;, &quot;Project ID&quot;, &quot;|&quot;, &quot;Project Name&quot;, &quot;|&quot;, &quot;Project Status&quot;));
System.out.println(String.format(&quot;%s&quot;, &quot;----------------------------------------------------------------------------------------------------------------&quot;));
}
public void printInvoice() {
System.out.println(String.format(&quot;%30s %25s %10.2f %25s %10s&quot;, this.getItemName(), &quot;| p&quot;, this.getPrice(), &quot;|&quot;, this.getQuantity()));
}
public static List&lt;Main&gt; buildInvoice() {
List&lt;Main&gt; itemList = new ArrayList&lt;&gt;();
itemList.add(new Main(&quot;01&quot;, 1, 20));
itemList.add(new Main(&quot;02&quot;, 2, 70));
itemList.add(new Main(&quot;03&quot;, 3, 45));
return itemList;
}
public static void main(String[] args) {
Main.printInvoiceHeader();
Main.buildInvoice().forEach(Main::printInvoice);
}
}

huangapple
  • 本文由 发表于 2020年10月18日 18:53:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/64412451.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定