gpt4 book ai didi

java - 将具有多种类型的数组列表与各自的 header 对齐

转载 作者:行者123 更新时间:2023-12-01 10:58:33 27 4
gpt4 key购买 nike

我正在通过单独类中的 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; 导入 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 for toString 返回格式化字符串。其格式与使用 printf 时的格式相同。

-编辑-尝试使用 %s 作为字符串。另外,也许 %f 代表 double 。小数点后的位数也是可调的。例如例如,如果您只想要小数点后两位数字,您可以说 %-3.2f

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

关于java - 将具有多种类型的数组列表与各自的 header 对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33467185/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com