代码之家  ›  专栏  ›  技术社区  ›  n0shadow

将Java输出格式化为表格

  •  2
  • n0shadow  · 技术社区  · 13 年前

    我试图以类似表格的格式输出程序存储的学生信息,因为它并不总是提供正确的间距。为了做到这一点,我遇到了 this question 并试图实现类似的解决方案。然而,当我试图以这种方式执行代码时,我的代码中的格式行出现了错误。

    public void displayStudents (){
        System.out.println ("\n-----------------------------");
        System.out.println ("Email System - Display Students");
        System.out.println ("-----------------------------");
        System.out.format("%10s%15d%15s%15s%20s", "Grade", "Last Name", "First Name", "Student Number", "Parent Email");
    
        StudentNode current = top;
        while (current != null){
            Student read = current.getStudentNode();
            System.out.format ("%10s%15d%15s%15s%20s", ""+read.getClass(), read.getLastName(), read.getFirstName(), ""+read.getStudentNum(), read.getParentEmail());
            //This will output with a set number of character spaces per field, giving the list a table-like quality
        }
    }//End of displayStudents
    

    代码的目标是以类似于下图的方式进行输出。 enter image description here

    请帮我找出我的错误。是否有其他方法可以执行此操作?

    谢谢

    编辑:我得到的错误是

    GradeException in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String
    at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source)
    at java.util.Formatter$FormatSpecifier.printInteger(Unknown Source)
    at java.util.Formatter$FormatSpecifier.print(Unknown Source)
    at java.util.Formatter.format(Unknown Source)
    at java.io.PrintStream.format(Unknown Source)
    at StudentList.displayStudents(StudentList.java:184)
    at OnlineCommunications.emailOption(OnlineCommunications.java:403)
    at OnlineCommunications.main(OnlineCommunications.java:451)
    

    需要注意的是,Grade是一个整数,Long是一个二重。

    2 回复  |  直到 13 年前
        1
  •  5
  •   Luiggi Mendoza    13 年前

    错误是因为 %d 用于数字非浮点值( int , long 等)。

    在打印标题的行中,必须使用 %XXs (其中XX是一个数字),因为你正在通过 String s作为参数:

    System.out.format("%10s%15s%15s%15s%20s",
        "Grade", "Last Name", "First Name", "Student Number", "Parent Email");
    

    while-loop ,您需要设置 %天 对于 整数 长的 变量,如年级和学号,无需将其转换为 一串 使用 "" + intProperty :

    System.out.format ("%10d%15s%15s%15d%20s",
        read.getClass(), read.getLastName(), read.getFirstName(),
        read.getStudentNum(), read.getParentEmail());
    

    由于看起来您想将输出格式化为向左(而不是向右),因此应该在XX数字之前添加一个hypen(-)符号:

    //similar for title
    System.out.format ("%-10d%-15s%-15s%-15d%-20s",
        read.getClass(), read.getLastName(), read.getFirstName(),
        read.getStudentNum(), read.getParentEmail());
    

    注:我假设 read.getClass() read.getStudentNum() 将返回 Grade Student number 值为 整数 长的 .

        2
  •  4
  •   Bernhard Barker    13 年前

    问题在于:

    10秒 %15天 %15s%15s%20s

    应该是:

    10秒 %15秒 %15s%15s%20s

    这是因为所有的输入参数 String 所以 d ( which applies to integral types only )无效。