Java Reference
In-Depth Information
Earlier in this chapter, you learned how to format the output on the standard output
device using the stream method
printf
. However, the method
printf
cannot be used
with output dialog boxes. Formatting the output in an output dialog box, particularly
decimal numbers, can be done using the
String
method
format
or the
class
DecimalFormat
. Next, we describe how to use the
String
method
format
.
Appendix D describes the
class
DecimalFormat
.
An expression to use the
String
method
format
is:
String.format(formatString, argumentList)
where the meaning of the parameters
formatString
and
argumentList
is the same as
in the method
printf
. The value of the expression is a formatted string. The following
example shows how the method
format
works.
EXAMPLE 3-13
Suppose we have the following declarations and initializations:
double
x = 15.674;
double
y = 235.73;
double
z = 9525.9864;
int
num = 83;
String str;
Expression Value
String.format("%.2f", x)
"15.67"
String.format("%.3f", y)
"235.730"
String.format("%.2f", z)
"9525.99"
String.format("%7s", "Hello")
" Hello"
String.format("%5d%7.2f", num, x)
" 83 15.67"
String.format("The value of num = %5d", num)
"The value of num
¼
83"
str = String.format("%.2f", z)
str
¼
"9525.99"
Because the value of the
String
method
format
is a string, the method
format
can also
be used as an argument to the methods
print
,
println
,or
printf
. Example 3-14
illustrates this concept.
EXAMPLE 3-14
public class
StringMethodformat
{
public static void
main (String[] args)
Search WWH ::
Custom Search