Format Printing

From Progzoo
Jump to: navigation, search

The printf method provides a powerful and succinct mechanism for solving many formatting problems.

The printf method

The printf method takes a formatting string followed by any number of additional parameters. The formatting string includes a number of escape sequences - each of these is substituted by the actual parameter given.
%s  is used when a string is expected
%d  is used when an integer (or long) is expected
%f  is used when a floating point number is expected

The result of

System.out.printf("The GDP of %s is %d.\n", name, gdp);

is

The GDP of United Kingdom is 1782000000000.
The GDP of Uganda is 39390000000.


[Font] [Default] [Show] [Resize] [History] [Profile]

Using printf to align

We can format output involving fixed and variable components. Usually we align strings to the left and numbers to the right.

Country: United Kingdom     GDP:    1,782,000,000,000
Country: Uganda             GDP:       39,390,000,000


In the printf a number of values may follow the format string. These values are used up by % placeholders in the format string.

The format string is
"Country: %-18s GDP: %,20d\n"
%-18s
the minus in -18 means align left,

the 18 means 18 characters are to be used, the s is for string.

%,20d
the comma means include , separator every three digits, the 20 means use 20 characters and align right, d is for decimal.
%9.2f
f is for floating point; it will use 9 spaces altogether including 2 decimal places
\n
This starts a new line.
[Font] [Default] [Show] [Resize] [History] [Profile]