Java Reference
In-Depth Information
L
ISTING
14.2
QuotientWithIf.java
1
import
java.util.Scanner;
2
3
public class
QuotientWithIf {
4
public static void
main(String[] args) {
5 Scanner input =
new
Scanner(System.in);
6
7
// Prompt the user to enter two integers
8 System.out.print(
"Enter two integers: "
);
9
int
number1 = input.nextInt();
reads two integers
10
int
number2 = input.nextInt();
11
12
if
(number2 !=
0
)
13 System.out.println(number1 +
" / "
+ number2
14 +
" is "
+ (
test
number2
number1 / number2
));
15
else
16 System.out.println(
"Divisor cannot be zero "
);
17 }
18 }
Enter two integers:
Divisor cannot be zero
5 0
To demonstrate the concept of exception handling, we can rewrite Listing 14.2 to compute a
quotient using a method, as shown in Listing 14.3.
L
ISTING
14.3
QuotientWithMethod.java
1
import
java.util.Scanner;
2
3
public class
QuotientWithMethod {
4
5
if
(number2 ==
0
) {
6 System.out.println(
"Divisor cannot be zero"
);
7
8 }
9
10
public static int
quotient(
int
number1,
int
number2) {
quotient method
System.exit(
1
);
terminate the program
return
number1 / number2;
11 }
12
13
public static void
main(String[] args) {
14 Scanner input =
new
Scanner(System.in);
15
16
// Prompt the user to enter two integers
17 System.out.print(
"Enter two integers: "
);
18
int
number1 = input.nextInt();
reads two integers
19
int
number2 = input.nextInt();
20
21
22 System.out.println(number1 +
" / "
+ number2 +
" is "
23 + result);
24 }
25 }
int
result = quotient(number1, number2);
invoke method