-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDivisionOperation.java
More file actions
51 lines (44 loc) · 1.74 KB
/
DivisionOperation.java
File metadata and controls
51 lines (44 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.util.Scanner;
// Custom exception for negative number input
class NegativeNumberException extends Exception {
public NegativeNumberException(String message) {
super(message);
}
}
// Custom exception for divide by zero
class DivideByZeroException extends Exception {
public DivideByZeroException(String message) {
super(message);
}
}
public class DivisionOperation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
// Read the numerator
System.out.print("Enter a positive integer numerator: ");
int numerator = scanner.nextInt();
if (numerator < 0) {
throw new NegativeNumberException("Numerator cannot be negative.");
}
// Read the denominator
System.out.print("Enter a positive integer denominator: ");
int denominator = scanner.nextInt();
if (denominator < 0) {
throw new NegativeNumberException("Denominator cannot be negative.");
}
if (denominator == 0) {
throw new DivideByZeroException("Denominator cannot be zero.");
}
// Perform division and display the result
double result = (double) numerator / denominator;
System.out.println("Result of division: " + result);
} catch (NegativeNumberException | DivideByZeroException e) {
System.out.println("Exception: " + e.getMessage());
} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
} finally {
scanner.close();
}
}
}