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

    效果如图:

  • 相关阅读:
    六、Doris数据流与控制流
    五、Doris数据分布
    非洛达芯片检测聚合教程NOT AIROHA CHIP
    慧联A8最新检测使用教程V2.0.3
    SpringBoot集成thymeleaf增删改查示例
    记一次Linux磁盘满盘/dev/vda1目录清理记录
    悦虎固件升级到底有啥用?二代为例
    PerfDog性能狗简介
    macOS常用命令
    像素格式与纹理压缩
  • 原文地址:https://www.cnblogs.com/wwssgg/p/15097674.html
Copyright © 2011-2022 走看看