简体   繁体   English

如何在Java中对齐下一行​​?

[英]How can I align the next lines in Java?

I can't figure out how to right align these columns in JAVA. 我无法弄清楚如何在JAVA中正确对齐这些列。 I tried several ways but none of them work. 我尝试了几种方法,但没有一种方法可行。 It works for other characters but not for Chinese. 它适用于其他角色,但不适用于中国人。

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" );

This is the expected result but even here it is not displayed correctly 这是预期的结果,但即使在这里也没有正确显示

冻结金额             XX 
投资中金额           XX
投资中金额额         XX
投资中金中金额       XX

You could (ab-)use the tai tou , full width space, "\ " : 你可以(ab-)使用tai tou ,全宽度空间, "\ "

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

Though with litte effort, you could do HTML output. 虽然经过努力,但您可以进行HTML输出。

There is nothing wrong with the Java code, only the way the output is displayed. Java代码没有任何问题,只有输出的显示方式。

The output is as follows: 输出如下:

冻结金额       XX 
投资中金额      XX 
投资中金额额     XX 
投资中金中金额    XX 

If you were actually to count the number of characters or do: 如果你实际上要计算字符数或做:

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());

You'd see that each line has the same length (14). 你会看到每一行都有相同的长度(14)。

The problem is that the display font doesn't show Chinese characters as the same size as other characters. 问题是显示字体不会显示与其他字符大小相同的中文字符。

I use this method, however I have no idea how it will work with Chinese characters: 我使用这种方法,但我不知道它如何与汉字一起使用:

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

Call it like so: padRight(StringToBePaddedToTheRight, intNumberOfPadsToTheRight); 像这样调用它: padRight(StringToBePaddedToTheRight, intNumberOfPadsToTheRight);

Thanks Guys 多谢你们

You are right, nothing wrong with the code only the editor configuration. 你是对的,代码只有编辑器配置没有错。

In my case I am using eclipse editor, I just change the default font for an Unicode. 在我的情况下,我使用的是eclipse编辑器,我只是更改了Unicode的默认字体。

冻结金额       XX
投资中金额      XX
投资中金额额     XX

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM