-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem1.java
More file actions
42 lines (37 loc) · 1.19 KB
/
problem1.java
File metadata and controls
42 lines (37 loc) · 1.19 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
public class Calculator {
// Inputs
private double a;
private double b;
private String operation;
// Constructor
public Calculator(double a, double b, String operation) {
this.a = a;
this.b = b;
this.operation = operation.toLowerCase(); // Normalize operation string
}
// Method to perform calculation
public double calculate() {
switch (operation) {
case "add":
return a + b;
case "subtract":
return a - b;
case "multiply":
return a * b;
case "divide":
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero.");
}
return a / b;
default:
throw new IllegalArgumentException("Invalid operation type.");
}
}
// Main method for testing
public static void main(String[] args) {
Calculator calc1 = new Calculator(10.5, 5.5, "add");
System.out.println("Result: " + calc1.calculate());
Calculator calc2 = new Calculator(20.0, 4.0, "divide");
System.out.println("Result: " + calc2.calculate());
}
}