将具有多个类型的数组列表与相应的标题

时间:2015-11-01 21:03:45

标签: java arraylist printf tostring

我打印出一个在每个标题下有多个参数的数组列表,通过一个单独的类中的toString方法,但我不知道如何格式化它以使它对齐。在这种情况下实施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;     import java.io. ;     import 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);
    }

}
}

1 个答案:

答案 0 :(得分:1)

您可以使用String.format for toString返回格式化的字符串。使用与使用printf相同的方式对其进行格式化。

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

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