我必须读取文件并显示一些数据。要读取的文件是:
Rory Williams
88
92
78
-1
James Barnes
87
76
91
54
66
-1
Sarah Jane Smith
92
86
95
85
82
-1
Jack Sparrow
18
54
13
0
-1
我显示人物统计信息的代码是:
public static void displayPersonStats(PrintWriter printWriter, String name,
int average, int median, int max, int min) {
// print person row
// printWriter.printf("%s \t\t%d\t%d\t%d\t%d\n", name, average, median,
// max, min);
//if min is one digit, it needs to be moved one more space to the right
if (min < 10) {
System.out.printf("%s \t\t %d %d %d %d\n", name, average, median, max, min);
//if digit is not one dgit it can follow below pattern
} else {
System.out.printf("%s \t\t %d %d %d %d\n", name, average, median, max, min);
}
}
输出:
Name Mean Median Max Min
------------------ ------ ------ ---- ----
Rory Williams 86 88 92 78
James Barnes 74 76 91 54
Sarah Jane Smith 88 86 95 82
Jack Sparrow 21 15 54 0
现在我只是打印到控制台而不是写入文件。正如你所看到的,Sarah Jane的行被搞砸了。当我用3个单词添加更多名称时,它做了同样的事情。任何有关修复此问题的帮助都表示赞赏。
答案 0 :(得分:1)
尝试使用格式打印:
System.out.printf("%-40s", name); ...
会为短名称添加额外的空格。
然后你还需要改变标题。
答案 1 :(得分:1)
像Ergonaut所写:
System.out.printf("%-20s %6d %6d %6d %6d\n", name, average, median, max, min);
您的输出将如下:
Name Mean Median Max Min
------------------ ------ ------ ---- ----
Rory Williams 86 88 92 78
James Barnes 74 76 91 54
Sarah Jane Smith 88 86 95 82
Jack Sparrow 21 15 54 0
Total number of participants: 4
Highest average score: Sarah Jane Smith (88)