-
Notifications
You must be signed in to change notification settings - Fork 0
/
Minus.java
50 lines (40 loc) · 1014 Bytes
/
Minus.java
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
package nz.ac.aut.wbz8656.dsa2017.assignment02;
import java.util.Objects;
/**
* A minus instruction. When executed, this should take the top two values on the stack passed in,
* subtract the second value from the first, and push the answer back on the stack
* @author Guan Wang
* @version 1.0
*/
public class Minus implements Instruction{
//Private
private Minus(){}
private static void checkNotEmpty (Stack<Long> stack, String name) {
if (stack.size() == 0) {
throw new IllegalArgumentException(name + " must not be empty");
}
}
//Factory
/**
* Creates a new minus instruction
* @return a new Minus object
*/
public static Minus make() {
return new Minus();
}
//Command
@Override
public void execute(Stack<Long> stack) {
Objects.requireNonNull(stack);
checkNotEmpty(stack, "Stack");
if (stack.size() == 1) {
return;
} else {
long a = stack.top();
stack.pop();
long b = stack.top();
stack.pop();
stack.push(b - a);
}
}
}