Java方法打印类似表格的内容

问答
如何用方法(继承以下知识的代码)打印出来图片这样的效果,省去横线,非常感谢!

img

可以定义一个类来表示一个明星的信息,然后使用这个类对象的数组来存储6个明星的具体信息,再在类中定义一个静态方法来格式化打印明星数组对象数组的信息即可。

代码如下(代码仅用于测试之用):

参考链接:


https://www.bbsmax.com/A/gAJGEZy4dZ/



public class PrintTableTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        Star [] stars = new Star[6];// 创建可以存储6个明星信息的Star类对象数组
        // 为每个数组元素赋值,具体内容可以再行修改
        stars[0] = new Star(1,"张三","wx@126.com","2010-02-02");
        stars[1] = new Star(2,"李四","wxyza@163.com","1988-12-26");
        stars[2] = new Star(3,"王五六","lmnop@gmail.com","1984-06-12");
        stars[3] = new Star(4,"赵六","tuvwx@sina.com","1986-06-13");
        stars[4] = new Star(5,"丁七","Jklmn@gmail.com","1955-07-14");
        stars[5] = new Star(6,"方八九十","rstu@163.com","1983-05-17");
        
        // 调用Star类的静态方法格式化打印明星数组里的信息
        Star.printStarArray(stars);
    }

}


class Star{   // 定义明星信息的类
    
    private int id;
    private String name;
    private String email;
    private String birth; 
    
    // 如果还有其他属性需要定义,可以在这里添加上,再把有参的构造方法,以及增加新增属性的get和set方法,
    //再修改下toString方法(如果不使用这个方法,也可以不修改)
    
    
    public Star() {
        
    }
    
    
    public Star(int id, String name, String email, String birth) {
        super();
        this.id = id;
        this.name = name;
        this.email = email;
        this.birth = birth;
    }

    // 格式化打印明星数组信息的静态方法
    public  static void printStarArray(Star [] stars) {
        
        if(stars==null||stars.length==0) {
            return ;
        }
        
        
        
        // https://www.zhihu.com/question/63474120/answer/209460221
        // https://www.bbsmax.com/A/gAJGEZy4dZ/
        // 格式化打印6个明星的信息
        for(int i=0;i<stars.length;i++) {
            if(stars[i]!=null) {
                if(i==0) {
                    // 表头
                    System.out.printf("%-8s %-7s\t%-18s%-12s\n","id","name","email","birth");
                }
                System.out.printf("%8d %-7s\t%-18s%-12s\n",
                stars[i].getId(),stars[i].getName(),stars[i].getEmail(),stars[i].getBirth());
            }
        }
    }

    public int getId() {
        return id;
    }


    public void setId(int id) {
        this.id = id;
    }


    public String getName() {
        return name;
    }


    public void setName(String name) {
        this.name = name;
    }


    public String getEmail() {
        return email;
    }


    public void setEmail(String email) {
        this.email = email;
    }


    public String getBirth() {
        return birth;
    }


    public void setBirth(String birth) {
        this.birth = birth;
    }


    @Override
    public String toString() {
        return "明星信息 [编号:" + this.getId() + ", 姓名:" + this.getName() + ", 邮箱:" 
                + this.getEmail() + ", 生日:" + this.getBirth() + "]";
    }


}


img

  • 你可以看下这个问题的回答https://ask.csdn.net/questions/7678729
  • 这篇博客也不错, 你可以看下JAVA代码实现按列表中元素的时间字段排序 左联表后缺失数据 多字段进行排序
  • 你还可以看下java参考手册中的 java-国际化 - 介绍如何设计软件,使其能够轻松适应(本地化)各种语言和地区。-引言定义了国际化一词,给出了一个快速的示例程序,并提供了一个检查表,你可以用来对现有程序进行国际化。-检查清单
  • 除此之外, 这篇博客: java代码自动生成数据库表中对应的类文件及操作数据库功能中的 方法(工具类): 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:

    • MyJDBCutil.autoGenerateAllBeanS(String url);
    • 参数:url – 生成class文件的路径
    • 作用:自动生成数据库中对应表中的类文件


    • MyJDBCutil.autoGenerateFormatBean(String table,String url);
    • 参数1:数据库中的表名
    • 参数2:生成class文件的路径
    • 作用:自动生成数据库中对应表中的类文件


    • 数据查询DQL(select)
    • Arrlist<E> list = MyJDBCutil.dql(String sql,Class<E> c,Object …obj);
    • 参数1:数据查询的sql语句
    • 参数2:需要查询的表对应的class文件
    • 参数3:sql语句“?”占位符所占位的元素
    • 返回值:对应的集合
    • 作用:查询方法,通过sql语句获取对应的集合


    • 数据操纵DML(delete/update/insert)
    • MyJDBCutil.dml(Connection con,String sql,Object … obj)
    • 参数1:事务的连接
    • 参数2:数据操纵的sql语句
    • 参数3:sql语句“?”占位符所占位的元素
    • 作用:支持事务的数据操纵方法


    - MyJDBCutil.dml(String sql,Object ... obj) - 参数1:数据操纵的sql语句 - 参数2:sql语句“?”占位符所占位的元素 - 作用:不支持事务的数据操纵方法
    package com.yunhe.util;
    
    import com.mchange.v2.c3p0.ComboPooledDataSource;
    
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.lang.reflect.Field;
    import java.sql.*;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Set;
    public class MyJDBCutil {
       private static ComboPooledDataSource dpds;
        static {
            //创建连接池对象加载配置文件
        dpds=new ComboPooledDataSource();
        }
        //返回一个新的连接
        public static Connection getCon() {
            Connection con = null;
            try {
                //使用连接池获取连接
                con=dpds.getConnection();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return con;
        }
    
        //更新方法
        public static int dml(String sql,Object ... obj)  {
            Connection con = getCon();//获取连接
            try {
                PreparedStatement ps = con.prepareStatement(sql);
                for (int i=0;i<obj.length;i++){
                    ps.setObject(i+1,obj[i]);
                }
                return ps.executeUpdate();
            }catch (Exception e){
                e.printStackTrace();
                return 0;
            }finally {
                close(con);
            }
        }
    
        //支持事务的更新方法
        public static int dml(Connection con,String sql,Object ... obj) throws SQLException {
            con.setAutoCommit(false);
                PreparedStatement ps = con.prepareStatement(sql);
                for (int i=0;i<obj.length;i++){
                    ps.setObject(i+1,obj[i]);
                }
                return ps.executeUpdate();
        }
    
        //查询方法
        public static <E> ArrayList<E> dql(String sql,Class<E> c, Object ...obj)  {
            Connection con = getCon();//获取连接
            ArrayList<E> list=new ArrayList<>();
            ResultSet rs=null;
            try {
                PreparedStatement ps = con.prepareStatement(sql);
                for (int i=0;i<obj.length;i++){
                    ps.setObject(i+1,obj[i]);
                }
                ResultSetMetaData metaData = ps.getMetaData();//获取查询元数据
                //元数据中包含所有关于本次sql查询的数据(不包含结果数据)
                //获取查询结果返回数据列的数目
                int columnCount = metaData.getColumnCount();
                //创建对应长度的数组用于保存相应的列名
                String [] colimNameArr=new String[columnCount];
                //循环获取指定列名名存储至数组中
                for (int i=0;i<colimNameArr.length;i++){
                    //  colimNameArr[i]=metaData.getColumnName(i+1);
                    colimNameArr[i]=metaData.getColumnLabel(i+1);
                }
                 rs = ps.executeQuery();
                while(rs.next()){
                    //使用反射调用泛型类的无参构造方法创建对象
                    E e= c.newInstance();
                    //数组循环获取对应列的数据
                    for (String colName:colimNameArr) {
                        Object value = rs.getObject(colName);//获取指定列的数据
                        //使用反射获取指定属性
                        //获取代表当前列  指定类的属性类型
                        //获取指定名称的代表指定属性的类型对象
                        Field declaredField = c.getDeclaredField(colName);
                        //为指定属性的类型对象授权 (私有属性必须授权后才能使用)
                        declaredField.setAccessible(true);
                        //为指定对象 对应属性赋值
                        declaredField.set(e,value);
                    }
                    list.add(e);
                }
                return list;
            }catch (Exception e){
                e.printStackTrace();
                return null;
            }finally {
                close(rs,con);
            }
        }
    
    
        //关闭方法
        public static void close(Connection con){
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        public static void close(ResultSet rs,Connection con){
            try {
                rs.close();
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    
        // 自动生成当前连接数据库所有bean对象保存至指定包下
        public static void autoGenerateAllBeanS(String beanUrl) {
            try {
                Connection con = getCon();
                String sql = "show tables";
                PreparedStatement ps = con.prepareStatement(sql);
                ResultSet rs = ps.executeQuery();
                while (rs.next()) {
                    autoGenerateFormatBean(rs.getString(1), beanUrl);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public static void autoGenerateFormatBean(String tables, String beanUrl) {
            String sql = "select * from " + tables;
    
            try {
                File directory = new File("");// 参数为空
                String courseFile = directory.getCanonicalPath();// 获取当前项目路径
                String replace = "src/" + beanUrl.replace(".", "/");
                String beanNane = tables.toUpperCase().charAt(0) + tables.substring(1);// 当前类名
                File file = new File(courseFile, replace + "/" + beanNane + ".java");// 当前类的文件对象
                file.createNewFile();
                Connection con = getCon();
                PreparedStatement ps = con.prepareStatement(sql);
                ResultSetMetaData metaData = ps.getMetaData();
                // 创建map集合 key为列名 value为对应的java类型
                HashMap<String, String> names = new HashMap<>();
                // 创建list集合存储所有的属性(顺序)
                ArrayList<String> nameList = new ArrayList<>();
    
                for (int i = 0; i < metaData.getColumnCount(); i++) {
                    String columnLabel = metaData.getColumnLabel(i + 1);// 获取指定列名
                    String columnTypeName = metaData.getColumnTypeName(i + 1);// 获取列类型
                    names.put(columnLabel, dbTOjava(columnTypeName));
                    nameList.add(columnLabel);
                }
    
                FileWriter fw = new FileWriter(file);
                BufferedWriter bw = new BufferedWriter(fw);
                // 书写包
                bw.write("package " + beanUrl + ";");
                bw.newLine();
                bw.newLine();
                // 书写导入包
                bw.write("import java.sql.*;");
                bw.newLine();
                bw.newLine();
                // 书写类名
                bw.write("public class " + beanNane + " {");
                bw.newLine();
                // 生成全部属性
                for (String key : nameList) {
                    String value = names.get(key);
                    bw.write("	private " + value + " " + key + ";");
                    bw.newLine();
                }
                bw.newLine();
                // 生成无参构造方法
                bw.write("	public " + beanNane + "() {");
                bw.newLine();
                bw.write("		super();");
                bw.newLine();
                bw.write("	}");
                bw.newLine();
                bw.newLine();
                // 生成全参构造方法
                bw.write("	public " + beanNane + "(");
                for (int i = 0; i < nameList.size(); i++) {
                    String key = nameList.get(i);
                    if (i != nameList.size() - 1) {
                        bw.write(names.get(key) + " " + key + ",");
                    } else {
                        bw.write(names.get(key) + " " + key);
                    }
                }
                bw.write(") {");
                bw.newLine();
                bw.write("		super();");
                bw.newLine();
    
                for (String key : nameList) {
                    bw.write("		this." + key + " = " + key + ";");
                    bw.newLine();
                }
                bw.write("	}");
                bw.newLine();
                bw.newLine();
                // 生成全部属性对应getset方法
                for (String key : nameList) {
                    String value = names.get(key);
                    bw.write("	public " + value + " get" + key.toUpperCase().charAt(0) + key.substring(1) + "() {");
                    bw.newLine();
                    bw.write("		return this." + key + ";");
                    bw.newLine();
                    bw.write("	}");
                    bw.newLine();
                    bw.newLine();
                    bw.write("	public void set" + key.toUpperCase().charAt(0) + key.substring(1) + "(" + value + " " + key
                            + ") {");
                    bw.newLine();
                    bw.write("		this." + key + " = " + key + ";");
                    bw.newLine();
                    bw.write("	}");
                    bw.newLine();
                    bw.newLine();
                }
    
                for (int i = 0; i < nameList.size(); i++) {
                    String string = nameList.get(i);
    
                    nameList.set(i, string + "= \"+ " + string + " + \"");
                }
                // 生成toString方法
                bw.write("	@Override");
                bw.newLine();
                bw.write("	public String toString() {");
                bw.newLine();
                bw.write("		return \"" + beanNane + " ");
                bw.write(nameList.toString());
                bw.write("\";");
                bw.newLine();
                bw.write("	}");
                bw.newLine();
                bw.write("}");
                bw.flush();
                bw.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        // 转换方法 将数据库列对象转换为指定java类型字符串
        private static String dbTOjava(String type) {
            if (type.equals("INT")) {
                return "int";
            } else if (type.equals("VARCHAR")||type.equals("CHAR")) {
                return "String";
            } else if (type.equals("DOUBLE")) {
                return "double";
            } else if (type.equals("FLOAT")) {
                return "float";
            }else if (type.equals("TIMESTAMP")||type.equals("DATETIME")||type.equals("DATE")||type.equals("TIME")){
                return "Timestamp";
            } else {
                return "Object";
            }
        }
    }
    
  • 您还可以看一下 汪翠老师的java项目实战之欢乐斗地主游戏开发教程 毕业项目课程设计带源码课程中的 给扑克牌绑定鼠标事件实现单击可以选择出牌列表小节, 巩固相关知识点