2015-12-05 70 views
0

我一直在尋找通過論壇找到一個確切的答案,但一直無法這樣做。這裏是我的代碼:Java格式化字符串間距

String item = String.format("%-6s $%-6.2f Number in Inventory: %-3d", this.getBarcode(), this.getPrice(), this.getInventory()); 

輸出看起來像這樣的兩個項目投入:

DR4423 $700.04 Number in Inventory: 24 
LD342 $1234.24 Number in Inventory: 425 

輸出應該是這樣的,在價格的數量額外字符空間清單排隊:

DR4423 $ 700.04 Number in Inventory: 24 
LD342 $1234.24 Number in Inventory: 425 

如何讓「庫存數量」排隊?它看起來像例子中的第一項失去了一個空的字符空間,因爲它只有5個數字而不是6個價格。先謝謝您的幫助。

+0

我需要那裏有正好6個字符的空間的價格。編輯問題以顯示預期輸出。 –

回答

3

我認爲你需要使用:

String.format("%-6s $%-7.2f Number in Inventory: %-3d", this.getBarcode(), this.getPrice(), this.getInventory()); 

或者,如果你想加入到前面的空間:

String.format("%-6s $%#7.2f Number in Inventory: %-3d", this.getBarcode(), this.getPrice(), this.getInventory()); 

通知的%-7而不是%-6。該時期被視爲一個角色。

+0

工作方式與\ t類似,沒有額外的選項卡空間。很好的答案,但我正在尋找$符號後的空間。 –

+0

@ javanewb2.0嘗試使用散列'#'而不是短劃線'-'。 :) –

+0

哈希#做了我所需要的。謝謝! –

1

在價格和'數字'之間插入\t應該適用於您的情況。

+0

我們使用'%s'的原因之一是爲了避免'\ t' ... – Pshemo

+0

這對我的預期輸出如何讀取有效,但我錯過了一個空間。當價格沒有6位數字時,我更新它在$和價格之間放置一個空格。這是我期待的格式。 –

1

%-6.2f-意味着你要通過數對齊到左,如:

|123,45| 
|123,40| 
|123,00| 
|12,00 | 
|1,00 | 

如果要調整您的號碼正確,如:

|123,45| 
|123,40| 
|123,00| 
| 12,00| 
| 1,00| 

只需刪除該-

你應該也可能應該設置最少使用長度7因爲.還需要一定的空間,這意味着生產

| 700.04| 
1234567 

需要7個字符。

所以請嘗試%-6s $%7.2f Number in Inventory: %-3d