Java Reference
In-Depth Information
The output to the console then looks like:
Text output with Formatter.
Primitives converted to strings:
boolean = false
byte = 114
short = 1211
int = 1234567
long
=
987654321
float
=
983.600
double
=
-4.30e-15
When we call the
Formatter
constructor,
System.out
,which references an
instance of
PrintStream
, must be cast to
OutputStream
because otherwise
there is an ambiguity over which constructor to use (since
PrintStream
imple-
ments
Appendable)
.
Note that you can directly obtain the formatted string created by the
Formatter
by invoking the
toString()
method. Also, if you simply want a
formatted string, such as for a graphical text component, and don't want to send it
to an output destination, you can create a
Formatter
with the no-argument con-
structor. The
Formatter
uses a
StringBuilder
(see Chapter 10) internally
to create the string, and you can access it via the
toString()
method.
9.4.3 Text input
While the print methods of
System.out
are simple and convenient to use, a
common complaint of new Java users has been the lack of a comparably simple
set of text input methods. Fortunately, J2SE 5.0 comes with the new
Scanner
class, which makes input much simpler. We discuss it in the next section. First
we look at the text input techniques available with Java 1.4 and earlier.
System.in
references an object with only the very limited capabilities of an
InputStream
.You can, for example, read in a single byte, which returns as an
int
value, or a byte array. You must cast each byte obtained from the keyboard
to a
char
type. For example:
try
{
int tmp
=
System.in.read ();
char c
=
(char) tmp;
}
catch (IOException e)
{}
Here a byte value is read and returned as the first byte in an
int
value. This
value is then converted to a
char
value. This operation assumes that the byte
corresponds to an 8-bit encoded character, such as an ASCII character. As for
Search WWH ::
Custom Search