Java Reference
In-Depth Information
TryFormattedOutput.java
This produces the following output on a new line:
a = 255 b = ff c = 377
You could equally well use "\n" in place of "%n" in the format string. The second and third format speci-
fiers use "<" as the argument index, so all three apply only to the value of the first argument. The arguments
b and c are ignored.
Note that if the format conversion is not consistent with the type of the argument to which you apply it,
an exception of type IllegalFormatConversion is thrown. This would occur if you attempted to output
any of the variables a , b , and c , which are of type int , with a specifier such as "%f" , which applies only to
floating-point values.
Specifying the Width and Precision
You can specify the field width for any output value. Here's an example of that:
int a = 5, b = 15, c = 255;
double x = 27.5, y = 33.75;
System.out.printf("x = %15f y = %8g", x, y);
System.out.printf("a = %1$5d b = %2$5x c = %3$2o", a, b, c);
TryFormattedOutput.java
Executing this results in the following output:
x = 27.500000 y = 33.750000 a = 5 b = f c = 377
You can see from the output that you get the width that you specify only if it is sufficient to accommodate
all the characters in the output value. The second floating-point value, y , occupies a field width of 9, not the
8 that is specified. When you want your output to line up in columns, you must be sure to specify a field
width that is sufficient to accommodate every output value.
Where the specified width exceeds the number of characters for the value, the field is padded on the left
with spaces so the value appears right-justified in the field. If you want the output left-justified in the field,
you just use the '-' flag character. For example:
System.out.printf("%na = %1$-5d b = %2$-5x c = %3$-5o", a, b, c);
This statement produces output left-justified in the fields, thus:
a = 5 b = f c = 377
You can add a precision specification for floating-point output:
double x = 27.5, y = 33.75;
System.out.printf("x = %15.2f y = %14.3f", x, y);
Here the precision for the first value is two decimal places, and the precision for the second value is 3
decimal places. Therefore, you get the following output:
x = 27.50 y = 33.750
Search WWH ::




Custom Search