英文:
How do I print in columns in java with printf?
问题
我正在尝试获得类似这样的结果:
Day Car 1 Car 2
1 3800.20 2200.42
2 2700.67 3678.14
3 2900.00 2694.47
我尝试在我的循环中实现这个(代码中字符串的第一行在循环外部,但外观相同,只是变量不同):
System.out.printf("%6d %6d %6d", Day, Car1, Car2);
但是我得到了错误。我希望列是左对齐的。
我该如何做到这一点?非常感谢!
英文:
I'm trying to get something that looks like this:
Day Car 1 Car 2
1 3800.20 2200.42
2 2700.67 3678.14
3 2900.00 2694.47
I've tried doing this in my for loop (the first line of code for the strings is outside of the for loop, but it looks the same just different variables):
System.out.printf("%6d %6d %6d",Day,Car1,Car2);
But I'm just getting errors. I'd like the columns to be left-aligned.
How would I do this? Thank you very much!
答案1
得分: 1
Object[][] a = {
{1, 3800.20, 2200.42},
{2, 2700.67, 3678.14},
{3, 2900.00, 2694.47}
};
System.out.printf("%3s %-9s %-9s%n", "Day", "Car1", "Car2");
for (Object[] r : a) {
System.out.printf("%-3d %-9.2f %-9.2f%n", r[0], r[1], r[2]);
}
输出:
Day Car1 Car2
1 3800.20 2200.42
2 2700.67 3678.14
3 2900.00 2694.47
英文:
To align the columns to the left, -
has to be used in the formatting pattern because by default the numerical columns are aligned to the right:
Object[][] a = {
{1, 3800.20, 2200.42},
{2, 2700.67, 3678.14},
{3, 2900.00, 2694.47}
};
System.out.printf("%3s %-9s %-9s%n", "Day", "Car1", "Car2");
for (Object[] r : a) {
System.out.printf("%-3d %-9.2f %-9.2f%n", r[0], r[1], r[2]);
}
Output:
Day Car1 Car2
1 3800.20 2200.42
2 2700.67 3678.14
3 2900.00 2694.47
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论