I've been looking through the forum to find an exact answer to this, but have been unable to do so. Here is my code:
String item = String.format("%-6s $%-6.2f Number in Inventory: %-3d", this.getBarcode(), this.getPrice(), this.getInventory());
The output looks like this for two items put in:
DR4423 $700.04 Number in Inventory: 24
LD342 $1234.24 Number in Inventory: 425
The output should look like this, with an extra character space in the price for Number in Inventory to line up:
DR4423 $ 700.04 Number in Inventory: 24
LD342 $1234.24 Number in Inventory: 425
How do I make the "Number in Inventory" line up? It looks like the first item in the example lost an empty character space as it only has 5 digits instead of 6 for the price. Thanks in advance for the help.
I think you need to use:
String.format("%-6s $%-7.2f Number in Inventory: %-3d", this.getBarcode(), this.getPrice(), this.getInventory());
Or, if you want the space added to the front:
String.format("%-6s $%#7.2f Number in Inventory: %-3d", this.getBarcode(), this.getPrice(), this.getInventory());
Notice the %-7
instead of %-6
. The period is counted as a character.
在价格和“数字”之间插入\\t
应该可以正常工作。
-
in %-6.2f
means you want passed number to be aligned to left, like:
|123,45|
|123,40|
|123,00|
|12,00 |
|1,00 |
If you want to align your number to right like:
|123,45|
|123,40|
|123,00|
| 12,00|
| 1,00|
then simply remove this -
.
You should should also probably set minimal used length to 7
since .
also takes some space which means that to produce
| 700.04|
1234567
you need 7 characters.
So try with %-6s $%7.2f Number in Inventory: %-3d
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.