简体   繁体   中英

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.

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.

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.

Good luck.

Syntax for string.format public static String format(String format, Object... 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. The number of arguments is variable and may be zero.

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.

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