forked from Kotlin-Polytech/FromKotlinToJava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArithmeticStack.java
More file actions
50 lines (41 loc) · 1.1 KB
/
Copy pathArithmeticStack.java
File metadata and controls
50 lines (41 loc) · 1.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
* $Id:$
*/
package part2.stack;
import java.util.Deque;
import java.util.LinkedList;
import java.util.function.BiFunction;
/**
* Arithmetic stack class
* @author Mikhail Glukhikh
*/
@SuppressWarnings("WeakerAccess")
public class ArithmeticStack {
private final Deque<Double> stack = new LinkedList<>();
public enum Operation {
PLUS,
MINUS,
TIMES,
DIV,
POWER;
public BiFunction<Double, Double, Double> getFunction() {
switch (this) {
case PLUS: return (x, y) -> x + y;
case MINUS: return (x, y) -> y - x;
case TIMES: return (x, y) -> x * y;
case DIV: return (x, y) -> y / x;
case POWER: return (x, y) -> Math.pow(y, x);
default: throw new AssertionError("Non-exhaustive when");
}
}
}
public void push(double x) {
stack.push(x);
}
public double top() {
return stack.peek();
}
public void execute(Operation op) {
stack.push(op.getFunction().apply(stack.pop(), stack.pop()));
}
}