-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculator.java
More file actions
33 lines (31 loc) · 960 Bytes
/
Calculator.java
File metadata and controls
33 lines (31 loc) · 960 Bytes
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
import java.util.function.BiFunction;
/**
* Example: Performs calculation based on key operation.
*
* Run with:
* bazel run //:cli -- file examples/Calculator.java "add" "10,20"
* bazel run //:cli -- file examples/Calculator.java "multiply" "5,7"
*/
public class Calculator implements BiFunction<String, String, Double> {
@Override
public Double apply(String operation, String numbers) {
String[] parts = numbers.split(",");
double a = Double.parseDouble(parts[0].trim());
double b = Double.parseDouble(parts[1].trim());
switch (operation.toLowerCase()) {
case "add":
return a + b;
case "subtract":
return a - b;
case "multiply":
return a * b;
case "divide":
if (b == 0) {
throw new ArithmeticException("Division by zero");
}
return a / b;
default:
throw new IllegalArgumentException("Unknown operation: " + operation);
}
}
}