将具有多种类型的数组列表与相应的 headers 对齐

Aligning an Array List with multiple types with respective headers

我正在通过单独的 class 中的 toString 方法在每个 header 下打印出一个包含多个参数的数组列表,但我不确定如何格式化它以使其对齐.在这种情况下执行 printf 的好方法是什么?好像真的

EmployeeFX(toString方法所在的位置):

package p20;

public class EmployeeFX
{

private static int id;
private String firstName;
private String lastName;
private boolean salaried;
private double salary;

public EmployeeFX(int id, String firstName, String lastName,boolean salaried, int salary)
{
    this.id=id;
    this.firstName=firstName;
    this.lastName=lastName;
    this.salaried=salaried;
    this.salary=salary;
}

public  int getId() {
    return id;
}

public String getFirstName() {
    return firstName;
}

public String getLastName() {
    return lastName;
}

public boolean isSalaried() {
    return salaried;
}

public double getSalary() {
    return salary;
}

public final String toString()
{
    String str;
    str=String.format("%-3d %-3d %-3d %-3d %-3d", getId(),getFirstName(),getLastName(), isSalaried(), getSalary());
    return str;
}

}

EmployeeOrderingDemo(输出将发生的地方) 包装 p20; 导入 java.io.; 导入 java.util.;

public class EmployeeOrderingDemo {

public static void main(String[] args)
{
    Scanner input=null;
    ArrayList<EmployeeFX> employeeList=new ArrayList<EmployeeFX>();
    try
    {
        FileReader Info=new FileReader("P01_DATA.txt");
        input=new Scanner(Info).useDelimiter("\s+");
    }
    catch(FileNotFoundException noFile)
    {
        System.out.println("Can't open file");
        System.exit(1);
    }

    input.nextLine();
    input.nextLine();
    try
    {
        while(input.hasNext())
        {
            employeeList.add(new EmployeeFX(input.nextInt(),input.next(),input.next(), input.nextBoolean(), input.nextInt()));

        }
    }
    catch(NoSuchElementException element)
    {
        System.err.println("Wrong type of file");
        element.printStackTrace();
        System.exit(1);
    }
    catch(IllegalStateException state)
    {
        System.err.println("Couldn't read from file");
        System.exit(1);
    }
    if(input!=null)
    {
        input.close();
    }

    outputData("Output in ORIGINAL order", employeeList, EmployeeOrdering.SALARIED);



}

public static void outputData(String str, ArrayList<EmployeeFX> employeeList, Comparator<EmployeeFX> specificComparator)
{
    String headerString=  "Id   FirstName   LastName    Salaried    Salary";//The headers themselves
    System.out.println("\n" + str + "\n\n" + headerString + "\n");
    Collections.sort(employeeList, specificComparator);
    for(EmployeeFX element:employeeList)
    {
        System.out.println(element);
    }

}
}

您可以将 String.format 用于 toString 到 return 格式化字符串。以与使用 printf 相同的方式对其进行格式化。

-EDIT- 为字符串尝试 %s。另外,也许 %f 是双倍的。小数点后的位数也是可调的。例如例如,如果您只想要小数点后两位数,您可以说 %-3.2f

如果这不能解决问题,请告诉我。