Java Reference
In-Depth Information
figure 2.15
Read two integers
and output
maximum using
Scanner
and no
exceptions
1
import java.util.Scanner;
2
3
class MaxTestA
4
{
5
public static void main( String [ ] args )
6
{
7
Scanner in = new Scanner( System.in );
8
int x, y;
9
10
System.out.println( "Enter 2 ints: " );
11
12
if( in.hasNextInt( ) )
13
{
14
x = in.nextInt( );
15
if( in.hasNextInt( ) )
16
{
17
y = in.nextInt( );
18
System.out.println( "Max: " + Math.max( x, y ) );
19
return;
20
}
21
}
22
23
System.err.println( "Error: need two ints" );
24
}
25
}
Using the various
next
and
hasNext
combinations from the
Scanner
gener-
ally works well, but can have some limitations. For instance suppose we want
to read two integers and output the maximum.
Figure 2.15 shows one idea that is cumbersome if we want to do proper
error checking, without using exceptions. Each call to
nextInt
is preceded by
a call to
hasNextInt
, and an error message is reached unless there are actually
two
int
s available on the standard input stream.
Figure 2.16 shows an alternative that does not use calls to
hasNextInt
.
Instead, calls to
nextInt
will throw a
NoSuchElementException
if the
int
is not
available, and this makes the code read cleaner. The use of the exception is
perhaps a reasonable decision because it would be considered unusual for the
user to not input two integers for this program.
Both options, however, are limited because in many instances, we might
insist that the two integers be entered on the same line of text. We might even
insist that there be no other data on that line. Figure 2.17 shows a different
option. A
Scanner
can be constructed by providing a
String
. So we can first
create a
Scanner
from
System.in
(line 7) to read a single line (line 12), and
then create a second
Scanner
from the single line (line 13) to extract the two
Search WWH ::
Custom Search