Java Reference
In-Depth Information
L ISTING 12.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();
read two integers
10
int number2 = input.nextInt();
11
12 if (number2 != 0 )
13 System.out.println(number1 + " / " + number2
14 + " is " + (number1 / number2));
15 else
16 System.out.println( "Divisor cannot be zero " );
17 }
18 }
test number2
Enter two integers: 5 0
Divisor cannot be zero
Before introducing exception handling, let us rewrite Listing 12.2 to compute a quotient using
a method, as shown in Listing 12.3.
L ISTING 12.3
QuotientWithMethod.java
1 import java.util.Scanner;
2
3 public class QuotientWithMethod {
4 public static int quotient( int number1, int number2) {
5 if (number2 == 0 ) {
6 System.out.println( "Divisor cannot be zero" );
7
quotient method
System.exit( 1 );
terminate the program
8 }
9
10
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();
read two integers
19
int number2 = input.nextInt();
20
21 int result = quotient(number1, number2);
22 System.out.println(number1 + " / " + number2 + " is "
23 + result);
24 }
25 }
invoke method
 
 
Search WWH ::




Custom Search