Page 208 - Introduction to Programming with Java: A Problem Solving Approach
P. 208

                174 Chapter 5 Using Pre-Built Methods Format Specifier Details
Format specifiers are powerful little critters. We won’t try to describe all of their power, but we’ll provide enough details to get you up and running. If you come across a formatting issue that you can’t resolve with our limited coverage, look up printf on Sun’s Java API Web site and search for format string details. But be prepared for lots of details. Sun provides a tremendous number of options with the printf method.
Here’s the syntax for a format specifier:
%[ flags][width][.precision]conversion-character
You’ve already seen the % symbol. It indicates the start of a format specifier. The flags, width, precision, and conversion character represent the different parts of a conversion specifier. Each of them specifies a different formatting trait. We’ll cover them in right-to-left order. Thus, we’ll describe the conversion char- acter first. But before jumping into conversion character details, note the square brackets. They indicate that something is optional. So the flags, width, and precision parts are optional. Only the % and the conversion character are required.
Conversion Character
The conversion character tells the JVM the type of data that is to be printed. For example, it might tell the JVM to print a string, or it might tell the JVM to print a floating-point number. Here is a partial list of con- version characters:
s
d
This displays a string.
f
This displays a decimal integer (an int or a long).
This displays a floating-point number (a float or a double) with a decimal point and at
e
least one digit to the left of the decimal point.
This displays a floating-point number (float or double) in scientific notation.
Apago PDF Enhancer
In explaining each part of a format specifier (conversion character, precision, width, and flags), we’ll provide short examples that illustrate the syntax and semantics. After we’re done with all the explanations, we’ll show a complete program example. Note this code fragment and its associated output:
System.out.printf("Planet: %s\n", "Neptune");
System.out.printf("Number of moons: %d\n", 13);
System.out.printf("Orbital period (in earth years): %f\n", 164.79);
System.out.printf(
"Average distance from the sun (in km): %e\n", 4498252900.0);
Ouput:
Planet: Neptune
Number of moons: 13
Orbital period (in earth years): 164.790000
Average distance from the sun (in km): 4.498253e+09
Note that by default, the f and e conversion specifiers generate six digits at the right of the decimal point.
    The f and e conversion specifiers print six digits by default.
             




































































   206   207   208   209   210