Java Reference
In-Depth Information
figure 2.18
Read exactly two
integers from the
same line and output
maximum using two
Scanner
s
1
class MaxTestD
2
{
3
public static void main( String [ ] args )
4
{
5
Scanner in = new Scanner( System.in );
6
7
System.out.println( "Enter 2 ints on one line: " );
8
try
9
{
10
String oneLine = in.nextLine( );
11
Scanner str = new Scanner( oneLine );
12
13
int x = str.nextInt( );
14
int y = str.nextInt( );
15
16
if( !str.hasNext( ) )
17
System.out.println( "Max: " + Math.max( x, y ) );
18
else
19
System.err.println( "Error: extraneous data on the line." );
20
}
21
catch( NoSuchElementException e )
22
{ System.err.println( "Error: need two ints" ); }
23
}
24
}
integers (lines 15 and 16). If anything goes wrong, a
NoSuchElementException
will be handled.
The use of the second
Scanner
in Figure 2.17 can work well and is conve-
nient; however, if it is important to ensure that there are no more than two
integers per line, we would need additional code. In particular, we would need
to add a call to
str.hasNext
()
, and if it returned true, we would know that
there is a problem. This is illustrated in Figure 2.18. There are other options,
such as the
split
method in
String
, as described in the exercises.
2.6.3
sequential files
One of the basic rules of Java is that what works for terminal I/O also works
for files. To deal with a file, we do not construct a
BufferedReader
object from
an
InputStreamReader
. Instead, we construct it from a
FileReader
object, which
itself can be constructed by providing a filename.
An example that illustrates these basic ideas is shown in Figure 2.19.
Here, we have a program that will list the contents of the text files that are
specified as command-line arguments. The
main
routine simply steps
through the command-line arguments, passing each one to
listFile
. In
FileReader
is used
for file input.
Search WWH ::
Custom Search