对齐Java中的printf输出Java、printf

2023-09-11 07:30:57 作者:从头再来

我需要显示其价格的项目从一个数组列表,并想调整价格。我几乎都有它的工作,但需要改进。下面是code和输出。任何想法如何使所有的价格一致?到目前为止,一些工作,但有些则没有。先谢谢了。

  // for循环
System.out.printf(%D%S \ t \ T $%2F \ N,
                i + 1的,BOOK_TYPE [I],造价[I]);
 

输出:

  1。报$ 1.00包装
2.纸张返回$ 7.50
3.精装书$ 10.00
4.电子书$ 2.00
5.杂志$ 3.00
 

解决方案 图文详解Java对象内存布局

您可以试试下面的例子。不要用 - 表示宽度之前,以确保左缩进。默认情况下,他们将是正确的缩进;这可能不适合你的目的。

  System.out.printf(%2D%-20s $%2F \ñ。我+ 1,BOOK_TYPE [I],成本[I]);
 

来源:http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

PS:这可能去当一个注释DWB的答案,但我仍然没有权限发表评论等回答它

I need to display a list of items with their prices from an array and would like to align the prices. I almost have it working but needs improvements. Below is the code and the output. Any ideas how to make all prices aligned? So far some work but some don't. Thanks in advance.

//for loop
System.out.printf("%d. %s \t\t $%.2f\n",
                i + 1, BOOK_TYPE[i], COST[i]);

output:

1. Newspaper         $1.00
2. Paper Back        $7.50
3. Hardcover book        $10.00
4. Electronic book       $2.00
5. Magazine          $3.00

解决方案

You can try the below example. Do use '-' before the width to ensure left indentation. By default they will be right indented; which may not suit your purpose.

System.out.printf("%2d. %-20s $%.2f\n",  i + 1, BOOK_TYPE[i], COST[i]);

Source: http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

PS: This could go as a comment to DwB's answer, but i still don't have permissions to comment and so answering it.