Java Reference
In-Depth Information
On some systems, you may get the following output for Sample Run 3:
Line 2: Enter the dividend: 2e
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:819)
at java.util.Scanner.next(Scanner.java:1431)
at java.util.Scanner.nextInt(Scanner.java:2040)
at java.util.Scanner.nextInt(Scanner.java:2000)
at ExceptionExample1.main(ExceptionExample1.java:14)
Next, consider Example 11-2. This is the same program as in Example 11-1, except that
in Line 8, using an if statement, a common programming practice, the program checks
whether divisor is zero. (Later in this chapter we will explain how to use Java's
mechanism to handle an InputMismatchException .)
EXAMPLE 11-2
import java.util.*;
public class ExceptionExample2
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int dividend, divisor, quotient;
//Line 1
System.out.print("Line 2: Enter the "
+ "dividend: ");
//Line 2
dividend = console.nextInt();
//Line 3
System.out.println();
//Line 4
System.out.print("Line 5: Enter the "
+ "divisor: ");
//Line 5
divisor = console.nextInt();
//Line 6
System.out.println();
//Line 7
if (divisor != 0)
//Line 8
{
quotient = dividend / divisor;
//Line 9
System.out.println("Line 10: "
+ "Quotient = "
+ quotient);
//Line 10
}
else
System.out.println("Line 11: Cannot "
+ "divide by zero."); //Line 11
}
}
Search WWH ::




Custom Search