Java Reference
In-Depth Information
As already mentioned, the
print
and
println
methods are used for for-
matted output. Any type can be converted to a
String
suitable for printing by
calling its
toString
method; in many cases, this is done automatically.
Unlike with C and C++, which have an enormous number of formatting
options, output in Java is done almost exclusively by
String
concatenation,
with no built-in formatting.
The predefined
streams are
System.in
,
System.out
, and
System.err
.
2.6.2
the
Scanner
type
The simplest method for reading formatted input is to use a
Scanner
. A
Scanner
allows the user to read lines one at a time using
nextLine
,
String
s one at a time
using
next
, or primitive types one at a time using methods such as
nextInt
and
nextDouble
. Prior to attempting to perform a read, it is customary to verify that
the read can succeed by using methods such as
hasNextLine
,
hasNext
,
hasNextInt
,
and
hasNextDouble
, which yield
boolean
results; as such there is typically less
need to deal with exception handling. When using a
Scanner
it is customary to
provide the import directive
import java.util.Scanner;
To use a
Scanner
that reads from the standard input we must first construct
a
Scanner
object from
System.in
. This was illustrated in Figure 2.11 at line 7.
In Figure 2.11, we see that
nextLine
is used to read a
String
, and then the
String
is converted to an
int
. From the discussion of
Scanner
in the previous
paragraph, we know there are several other options.
An alternative option, which is perhaps the cleanest, is the follow-
ing replacement, which avoids exceptions entirely, and uses
nextInt
and
hasNextInt
:
System.out.println( "Enter an integer: " );
if( in.hasNextInt( ) )
{
x = in.nextInt( );
System.out.println( "Half of x is " + ( x / 2 ) );
}
else
{ System.out.println("Integer was not entered." }
Search WWH ::
Custom Search