如何在Java中使用printf按列打印?

huangapple go评论63阅读模式
英文:

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  

huangapple
  • 本文由 发表于 2020年9月7日 02:38:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63767656.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定