String.format()是要走的路。它的第一个参数是格式字符串,它使用格式说明符来指定数据类型和其他标志来控制文本对齐、精度等。
这是一个简单的表实现,可以帮助您入门。
用户等级:
public class User {
private String name;
private int age;
private float height;
public User(String name, int age, float height) {
this.name = name;
this.age = age;
this.height = height;
}
@Override
public String toString() {
return String.format("%-20s | %5d | %5.2f", name, age, height);
}
private static String getTableHeader() {
StringBuilder sb = new StringBuilder(String.format(
"%-20s | %5s | %5s", "Name", "Age", "Height"));
char[] line = new char[sb.length()];
Arrays.fill(line, '-');
return sb.append("\n").append(new String(line)).toString();
}
public static void printUserTable(ArrayList<User> users) {
System.out.println(getTableHeader());
for (User user : users) {
System.out.println(user);
}
}
}
主程序
public static void main(String[] args) {
ArrayList<User> users = new ArrayList<User>();
users.add(new User("Gus Smith", 22, 5.11f));
users.add(new User("Hank Mathewson", 42, 6.1f));
users.add(new User("Frank Dimitrianus", 54, 5.6f));
User.printUserTable(users);
}
输出
Name | Age | Height
-------------------------------------
Gus Smith | 22 | 5.11
Hank Mathewson | 42 | 6.10
Frank Dimitrianus | 54 | 5.60
我想你可以从这里开始。可能应该首先将高度打印为5'11"
.