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

    效果如图:

  • 相关阅读:
    android判断服务是否是运行状态
    Android调用OCR识别图像中的文字
    Java生成各种条形码
    android 实现摇一摇功能
    【读书笔记】Html5游戏开发
    SpeechLib 语音播报
    罗盘
    注释文档在线编辑及生成
    系统空闲时间判断&命名验证
    Asp.Net MVC中使用ACE模板之Jqgrid
  • 原文地址:https://www.cnblogs.com/wwssgg/p/15097674.html
Copyright © 2011-2022 走看看