代码优化

This commit is contained in:
SunYu 2020-09-30 13:50:13 +08:00
parent 7c23aadb9e
commit 93877205c5
2 changed files with 149 additions and 153 deletions

View File

@ -19,6 +19,7 @@ public class ConsoleTable {
private static final char COLUMN_LINE = '|';
private static final char CORNER = '+';
private static final char SPACE = '\u3000';
private static final char LF = '\n';
/**
* 表格头信息
@ -89,12 +90,26 @@ public class ConsoleTable {
public String toString() {
StringBuilder sb = new StringBuilder();
fillBorder(sb);
for (List<String> headers : HEADER_LIST) {
for (int i = 0; i < headers.size(); i++) {
fillRow(sb, HEADER_LIST);
fillBorder(sb);
fillRow(sb, BODY_LIST);
fillBorder(sb);
return sb.toString();
}
/**
* 填充表头或者表体信息
*
* @param sb
* @param list 表头列表或者表体列表
*/
private void fillRow(StringBuilder sb, List<List<String>> list) {
for (List<String> r : list) {
for (int i = 0; i < r.size(); i++) {
if (i == 0) {
sb.append(COLUMN_LINE);
}
String header = headers.get(i);
String header = r.get(i);
sb.append(SPACE);
sb.append(header);
sb.append(SPACE);
@ -107,31 +122,8 @@ public class ConsoleTable {
}
sb.append(COLUMN_LINE);
}
sb.append('\n');
sb.append(LF);
}
fillBorder(sb);
for (List<String> bodys : BODY_LIST) {
for (int i = 0; i < bodys.size(); i++) {
if (i == 0) {
sb.append(COLUMN_LINE);
}
String body = bodys.get(i);
sb.append(SPACE);
sb.append(body);
sb.append(SPACE);
int l = body.length();
int lw = columnCharNumber.get(i);
if (lw > l) {
for (int j = 0; j < (lw - l); j++) {
sb.append(SPACE);
}
}
sb.append(COLUMN_LINE);
}
sb.append('\n');
}
fillBorder(sb);
return sb.toString();
}
/**
@ -145,7 +137,7 @@ public class ConsoleTable {
sb.append(Convert.toSBC(StrUtil.fillAfter("", ROW_LINE, width + 2)));
sb.append(CORNER);
}
sb.append('\n');
sb.append(LF);
}
/**

View File

@ -7,7 +7,7 @@ public class ConsoleTableTest {
@Test
@Ignore
public void printTest(){
public void printTest() {
ConsoleTable t = new ConsoleTable();
t.addHeader("姓名", "年龄");
t.addBody("张三", "15");
@ -15,6 +15,8 @@ public class ConsoleTableTest {
t.addBody("王二麻子", "37");
t.print();
Console.log();
t = new ConsoleTable();
t.addHeader("体温", "占比");
t.addHeader("", "%");
@ -22,6 +24,8 @@ public class ConsoleTableTest {
t.addBody("37", "5");
t.print();
Console.log();
t = new ConsoleTable();
t.addHeader("标题1", "标题2");
t.addBody("12345", "混合321654asdfcSDF");