Java Reference
In-Depth Information
figure 2.16
Read two integers
and output maximum
using
Scanner
and
exceptions
1
class MaxTestB
2
{
3
public static void main( String [ ] args )
4
{
5
Scanner in = new Scanner( System.in );
6
7
System.out.println( "Enter 2 ints: " );
8
9
try
10
{
11
int x = in.nextInt( );
12
int y = in.nextInt( );
13
14
System.out.println( "Max: " + Math.max( x, y ) );
15
}
16
catch( NoSuchElementException e )
17
{ System.err.println( "Error: need two ints" ); }
18
}
19
}
1
import java.util.Scanner;
2
3
public class MaxTestC
4
{
5
public static void main( String [ ] args )
6
{
7
Scanner in = new Scanner( System.in );
8
9
System.out.println( "Enter 2 ints on one line: " );
10
try
11
{
12
String oneLine = in.nextLine( );
13
Scanner str = new Scanner( oneLine );
14
15
int x = str.nextInt( );
16
int y = str.nextInt( );
17
18
System.out.println( "Max: " + Math.max( x, y ) );
19
}
20
catch( NoSuchElementException e )
21
{ System.err.println( "Error: need two ints" ); }
22
}
23
}
figure 2.17
Read two integers
from the same line
and output maximum
using two
Scanner
s
Search WWH ::
Custom Search