java生成控制台表格的源码
时间: 2023-12-20 18:17:02 浏览: 123
生成控制台表格的 Java 代码可以使用以下的实现方式:
```java
import java.util.ArrayList;
import java.util.List;
public class ConsoleTable {
private List<String[]> rows = new ArrayList<>();
private int[] columnWidths;
public void addRow(String... cells) {
rows.add(cells);
if (columnWidths != null) {
for (int i = 0; i < cells.length; i++) {
columnWidths[i] = Math.max(columnWidths[i], cells[i].length());
}
}
}
public void print() {
if (rows.isEmpty()) {
return;
}
int numColumns = rows.get(0).length;
columnWidths = new int[numColumns];
for (String[] row : rows) {
for (int i = 0; i < numColumns; i++) {
columnWidths[i] = Math.max(columnWidths[i], row[i].length());
}
}
int totalWidth = numColumns + 1;
for (int width : columnWidths) {
totalWidth += width;
}
for (int i = 0; i < totalWidth; i++) {
System.out.print("-");
}
System.out.println();
for (String[] row : rows) {
System.out.print("| ");
for (int i = 0; i < numColumns; i++) {
System.out.print(String.format("%-" + columnWidths[i] + "s | ", row[i]));
}
System.out.println();
}
for (int i = 0; i < totalWidth; i++) {
System.out.print("-");
}
System.out.println();
}
}
```
该类提供了 `addRow` 方法用于添加一行数据,以及 `print` 方法用于打印表格。例如,可以使用以下代码调用该类:
```java
ConsoleTable table = new ConsoleTable();
table.addRow("Name", "Age", "Gender");
table.addRow("Alice", "25", "Female");
table.addRow("Bob", "30", "Male");
table.addRow("Charlie", "20", "Male");
table.print();
```
这将在控制台中输出以下表格:
```
+---------+-----+--------+
| Name | Age | Gender |
+---------+-----+--------+
| Alice | 25 | Female |
| Bob | 30 | Male |
| Charlie | 20 | Male |
+---------+-----+--------+
```
注意,这里使用了 `+` 和 `-` 符号来绘制表格的边框,可以根据需要进行修改。
阅读全文