Java Reference
In-Depth Information
For example, you could write the following to output floating-point values:
double x = 27.5, y = 33.75;
String outString = String.format("x = %15.2f y = %14.3f", x, y);
outString
contains the data formatted according to the first argument to the
format()
method. You
could pass
outString
to the
print()
method to output it to the command line:
System.out.print(outString);
You get the following output:
x = 27.50 y = 33.750
This is exactly the same output as you got earlier using the
printf()
method, but obviously
outString
is available for use anywhere.
You can use a
java.util.Formatter
object directly to format data. You first create the
Formatter
ob-
ject like this:
StringBuffer buf = new StringBuffer();
java.util.Formatter formatter = new java.util.Formatter(buf);
The
Formatter
object generates the formatted string in the
StringBuffer
object
buf
— you could also
use a
StringBuilder
object for this purpose, of course. You now use the
format()
method for the
format-
ter
object to format your data into
buf
like this:
double x = 27.5, y = 33.75;
formatter.format("x = %15.2f y = %14.3f", x, y);
If you want to write the result to the command line, the following statement does it:
System.out.print(buf);
The result of executing this sequence of statements is exactly the same as from the previous fragment.
A
Formatter
object can format data and transfer it to destinations other than
StringBuilder
and
StringBuffer
objects, but I defer discussion of this until I introduce file output in Chapter 10.
SUMMARY
In this chapter, I have introduced the facilities for inputting and outputting basic types of data to a stream.
You learned how to read data from the keyboard and how to format output to the command line. Of course,
you can apply these mechanisms to any character stream. You work with streams again when you learn
about reading and writing files.
EXERCISES
You can download the source code for the examples in the topic and the solutions to the following exer-
1.
Use a
StreamTokenizer
object to parse a string entered from the keyboard containing a series of data
items separated by commas and output each of the items on a separate line.