代码如下:
public class Table { private static StringBuffer contentSb = new StringBuffer(); //调整每列的宽度 private static Integer[] widths = new Integer[] {10,30,50}; static void print_table(String name, String course, String score) { String[] table = {name, course, score}; for (int i = 0; i < 3; ++i) { int size = widths[i]; contentSb.append("|"); int len = table[i].length(); // int left_space = ① ; int left_space = (size-len)%2==0 ?(size-len)/2 :(size-len)/2+1 ; // int right_space = ② ; int right_space = (size-len)/2 ; // for (int j = 0; j < ③ ; ++j) { //左边空格 for (int j = 0; j < left_space ; ++j) { contentSb.append(" "); } contentSb.append(table[i]); //右边空格 // for (int j = 0; j < ④ ; ++j) { for (int j = 0; j < right_space ; ++j) { contentSb.append(" "); } } contentSb.append("| "); for (int i = 0; i < 3; ++i) { contentSb.append("+"); for (int j = 0; j < widths[i]; ++j) { contentSb.append("-"); } } contentSb.append("+ "); } public static void main(String[] args) { //第一行输出 for (int i = 0; i < 3; ++i) { contentSb.append("+"); for (int j = 0; j < widths[i]; ++j) { contentSb.append("-"); } } contentSb.append("+ "); print_table("name", "course", "score"); print_table("barty", "math", "100"); print_table("islands", "English", "60"); print_table("wudi", "Chinese", "99"); print_table("islands", "Physics", "100"); System.out.println(contentSb.toString()); } }
效果如图: