简体   繁体   English

Java中String.format的用法

[英]Usage of String.format in Java

What I wanted to print: 我要打印的内容:

Coca-Cola      $ 11.00
Pepsi           $ 9.45
Sprite          $ 8.50

What end up printing: 最终打印什么:

Coca-Cola       $ 11
Pepsi       $ 9.45
Sprite       $ 8.5

My code: 我的代码:

public void test(){
    for (int i = 0; i<20; i++){
        System.out.print(product[i]);
        System.out.println(String.format("%20s%n", "$ "+price[i]));;

    }

I am looking for this for like 2 hours, perhaps I'm not that good specifying my search terms, but I'll try to avoid some more hours of searching and suffering by simply asking... Sorry for not knowing enough to properly find this on the forums or specify my title and thank you very much. 我正在寻找大约2个小时的时间,也许我指定的搜索条件不太好,但是我会通过简单地询问来避免更多的搜索时间和痛苦。在论坛上指定此标题或指定我的头衔,非常感谢。

The problem of your code is that it first prints the product then it try to print a formatted string. 您的代码的问题在于,它首先打印产品, 然后尝试打印格式化的字符串。

The battle is already lost when it print those things separately. 当单独打印这些东西时,战斗已经失败了。 Because the second print needs to know the length of the product to determine how many spaces it needs to align the prices. 因为第二张印刷品需要知道产品的长度,才能确定需要多少个空间以对齐价格。 That number is definitely not going to be the same. 这个数字肯定不会相同。

Try this instead: 尝试以下方法:

System.out.printf("%-20s$ %5.2f\n", product[i], price[i]);

Output: 输出:

Coca-Cola           $ 11.00
Pepsi               $  9.45
Sprite              $  8.50

The %-20s will left justify the product name, fill required number of spaces after the product name. %-20s将左对齐产品名称,并在产品名称后填写所需的空格。

To align the decimal point, we need to specify the total length of the formatted number as well. 为了对齐小数点,我们还需要指定格式化数字的总长度。 With %5.2 , we ask for a total length of 5, which 11.00 fits well, you can tune up this number if price is greater than 99. 使用%5.2 ,我们要求总长度为5,这很适合11.00 ,如果价格大于99,则可以调整此数字。

Good luck. 祝好运。

Syntax for string.format public static String format(String format, Object... args) string.format公共静态字符串格式的语法(字符串格式,对象... args)

Parameters 参量

format-This is a format string. 格式-这是格式字符串。 args- This is the argument referenced by the format specifiers in the format string.If there are more arguments than format specifiers, the extra arguments are ignored. args-这是格式字符串中格式说明符引用的参数。如果参数多于格式说明符,则多余的参数将被忽略。 The number of arguments is variable and may be zero. 参数的数量是可变的,可以为零。

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

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