像表一样格式化Java输出

n0s*_*dow 2 java formatting

我试图以类似于表格的格式输出关于我的程序存储的学生的信息,因为\ t并不总是提供正确的间距.为了做到这一点,我遇到了这个问题并试图启用类似的解决方案.但是,当我尝试执行它时,我在代码中获取格式行的错误.

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
Run Code Online (Sandbox Code Playgroud)

代码的目标是以类似于下图的方式输出. 在此输入图像描述

请帮助我找到我的错误.是否有一种替代方法可以执行此操作?

谢谢.

编辑:我得到的错误是

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)
Run Code Online (Sandbox Code Playgroud)

应该注意,Grade是一个整数,Long是一个整数.

Lui*_*oza 5

该错误是因为%d对于数值非浮点值(int,long等).

在您打印标题的行中,您必须使用%XXs(其中XX是数字),因为您将Strings作为参数传递:

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

在里面的线while-loop,你需要设置%dintlong变量,如等级和学号,就没有必要将其转换为String使用"" + intProperty:

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

由于看起来您想要将输出格式化为左侧(而不是右侧),您应该在XX号码之前添加一个超级( - )符号:

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

注意:我假设read.getClass()并将和值read.getStudentNum()返回为或.GradeStudent numberintlong