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

    效果如图:

  • 相关阅读:
    归并排序(非递归)
    centos7.2 安装jenkins2.274
    归并排序
    Jmeter5.4支持TPS测试
    centos下安装rocketmq4.6.1
    Java 8新特性:lambda表达式
    tomcat putty启动
    Linux启动tomcat带控制台
    每个Java开发者都应该知道的5个JDK工具
    强大易用的日期和时间库 线程安全 Joda Time
  • 原文地址:https://www.cnblogs.com/wwssgg/p/15097674.html
Copyright © 2020-2023  润新知