英文:
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 ="";
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";
}
答案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 = "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;
}
}
答案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 = { "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 |
答案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("%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);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论