-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathOperator.java
More file actions
35 lines (29 loc) · 1 KB
/
Operator.java
File metadata and controls
35 lines (29 loc) · 1 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
package computation;
import exception.ZeroDivisionException;
import java.util.Arrays;
import java.util.function.BiFunction;
public enum Operator {
ADD("+", (num1, num2) -> num1 + num2),
SUBTRACT("-", (num1, num2) -> num1 - num2),
MULTIPLY("*", (num1, num2) -> num1 * num2),
DIVIDE("/", (num1, num2) -> {
if (num2 == 0)
throw new ZeroDivisionException();
return num1 / num2;
});
private final String operator;
private final BiFunction<Integer, Integer, Integer> expression;
Operator(String operator, BiFunction<Integer, Integer, Integer> expression) {
this.operator = operator;
this.expression = expression;
}
public static Operator getOperator(String getString) {
return Arrays.stream(Operator.values())
.filter(s -> s.operator.equals(getString))
.findFirst()
.get();
}
public int operate(Integer num1, Integer num2) {
return expression.apply(num1, num2);
}
}