2013-09-23 40 views
3

我無法弄清楚如何在JAVA中將這些列對齊。我嘗試了幾種方法,但都沒有工作。它適用於其他角色,但不適用於中文。如何對齊Java中的下一行?

String line1="凍結金額"; 
String line2="投資中金額"; 
String line3="投資中金額額"; 
String line4="投資中金中金額"; 
System.out.format("%-10s %s %n",line1, "XX"); 
System.out.format("%-10s %s %n",line2, "XX"); 
System.out.format("%-10s %s %n",line3, "XX"); 
System.out.format("%-10s %s %n",line4, "XX"); 

這是預期的結果,但即使在這裏沒有正確

凍結金額    XX 
投資中金額   XX 
投資中金額額   XX 
投資中金中金額  XX 
+0

請舉一個例子,說明你不想輸出! – tilpner

+0

顯然對齊。這是一個10字符寬度的列,右對齊。 –

回答

0

沒有什麼錯的Java代碼,只顯示輸出的方式顯示。

輸出如下:

凍結金額  XX 
投資中金額  XX 
投資中金額額  XX 
投資中金中金額 XX 

如果你實際上計數的字符數或做:

System.out.println(String.format("%-10s %s ",line1, "XX").length()); 
System.out.println(String.format("%-10s %s ",line2, "XX").length()); 
System.out.println(String.format("%-10s %s ",line3, "XX").length()); 
System.out.println(String.format("%-10s %s ",line4, "XX").length()); 

你會看到,每一行都有相同的長度(14 )。

問題是顯示字體不顯示與其他字符相同大小的中文字符。

3

你可以(AB-)使用tai tou,全寬空間,"\u3000"

System.out.println(String.format("%-10s %s",line1, "XX").replace(" ", "\u3000")); 

雖然與豆蔻的努力,你可以做的HTML輸出。

+0

雖然使用此解決方案,但使用非中文字符的字符串將無法正確格式化。可能沒有適用於兩者的解決方案。 – Dukeling

+0

@Dukeeling好點,除此之外還有其他的功能。 –

0

我用這個方法,但是我不知道它如何與中國文字工作:

public String padRight(String s, int n) 
{ 
    return String.format("%1$-" + n + "s", s); 
} 

說它像這樣:padRight(StringToBePaddedToTheRight, intNumberOfPadsToTheRight);

+0

謝謝,我已經試過這個,但是,我得到了同樣的問題。 – pablo

0

謝謝你們

你是對的,什麼錯誤的代碼只有編輯器配置。

在我的情況下,我使用eclipse編輯器,我只是更改Unicode的默認字體。

凍結金額       XX 
投資中金額      XX 
投資中金額額     XX 
相關問題