zoukankan      html  css  js  c++  java
  • JAVA输出表格

    代码如下:

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

    效果如图:

  • 相关阅读:
    树的遍历
    动态规划之背包问题
    Dijkstra算法
    最短路径
    关于数学公式Markdown
    子集数
    O、Θ、Ω
    AT212 P-CASカードと高橋君
    vector的使用方法
    P3512 [POI2010]PIL-Pilots 单调队列的应用
  • 原文地址:https://www.cnblogs.com/wwssgg/p/15097674.html
Copyright © 2011-2022 走看看