Java Reference
In-Depth Information
System.out.println(i);
}
public static int
getNumber ()
{
try
{
Scanner console =
new
Scanner(System. in) ;
System. out . print (
"Enter a positive integer: "
);
return
console . nextInt() ;
}
catch
(InputMismatchException exception)
{
return
−
1;
}
}
}
The
getNumber
method asks the user to enter an integer and reads the integer. How-
ever, the
nextInt
method will raise an exception if the user does not enter an integer. An
exception is an object that is automatically generated by Java. Every exception belongs to
an exception class. For example,
InputMismatchException
is an exception class. An ex-
ception of type
InputMismatchException
is generated when Java expects an input of one
type (e.g., an integer), but receives an input of a different type (e.g., a string). All exception
classes inherit from the
Exception
class. In the above code, the exception object is passed
as a parameter in the
catch
statement, but not used.
To handle an exception, create a
try
block. The
try
block must be followed by
either one or more
catch
blocks, a
finally
block, or both. The
finally
block, when
present, must be the last block in the statement.
An
InputMismatchException
is generated by the call to the
nextInt
method when the
user does not enter an integer. This exception is handled in the
catch
part of the statement.
As a result, the
getNumber
method returns
1 when the user does not enter an integer.
This signals to the
main
method that something went wrong and the user is required to
enter the integer again. In order for this approach to work, we assume that the user must
enter a positive integer.
Next, suppose that we require that the user enters an arbitrary integer, not just a
positive integer. In this case, the
getNumber
method should return two pieces of data: the
integer that is entered (assuming it is an integer) and a Boolean value that tells us if the
user entered an integer. Of course, as we already know, a method cannot return two pieces
of data. The only way to circumvent this restriction is to give the method an address where
to write the result. Here is the new implementation.
−
import
java . util .
∗
;
public class
Test
{
public static void
main(String args [])
{
int
a[] =
new i n t
[1];
int
i;
while
( ! getNumber(a) ) ;
i=a[0];
System.out.println(i);
}
public static boolean
getNumber(
int
[] a)
{