Page 592 - Introduction to Programming with Java: A Problem Solving Approach
P. 592
558 Chapter 14 Exception Handling
/***************************************************************
*
LuckyNumber.java
Dean & Dean
This program reads the user's lucky number as an int.
***************************************************************/
*
*
*
import java.util.Scanner;
import java.util.InputMismatchException;
public class LuckyNumber
{
}
// end LuckyNumber class
public static void main(String[] args)
{
}
// end main
Scanner stdIn = new Scanner(System.in);
int num; // lucky number
try
{
System.out.print("Enter your lucky number (an integer): ");
num = stdIn.nextInt();
}
catch (InputMismatchException e)
{
}
System.out.priAntplna(go PDF Enhancer
"Invalid entry. You'll be given a random lucky number.");
num = (int) (Math.random() * 10) + 1;
// between 1-10
System.out.println("Your lucky number is " + num + ".");
Sample session 1:
Enter your lucky number (an integer): 27
Your lucky number is 27.
Sample session 2:
Enter your lucky number (an integer): 33.42
Invalid entry. You'll be given a random lucky number.
Your lucky number is 8.
Import InputMismatchException for use below.
The e parameter receives an InputMismatchException object.
Figure 14.1 LuckyNumber program that uses try and catch blocks for numeric user entry
In this example, the JVM instantiates an InputMismatchException object. The JVM then passes the InputMismatchException object to the catch block heading’s e parameter. Since e is declared to be an InputMismatchException and InputMismatchException is not part of the core Java lan- guage, at the top of the program we need to include:
import java.util.InputMismatchException;