/
MyStack.java
77 lines (63 loc) · 1.95 KB
/
MyStack.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
* Author: Kenneth Truex, ktruex2012@my.fit.edu
* Course: CSE 1002, Section 02, Spring 2013
* Project: Proj 23, stack
*/
import java.util.Scanner;
public class MyStack<T> implements Stack<T> {
private int size;
private final int maxSize;
private final T[] stack;
@SuppressWarnings("unchecked")
public MyStack(final int theMaxSize) {
maxSize = theMaxSize;
stack = (T[]) new Object[maxSize];
size = 0;
}
@Override
public final boolean isEmpty() {
return size == 0;
}
@Override
public final T pop() throws BufferEmptyException {
if (isEmpty()) {
throw new BufferEmptyException();
}
final T item = stack[size - 1];
stack[size - 1] = null;
size--;
System.out.println("pop " + item.toString());
return item;
}
@Override
public final void push(final T item) throws BufferFullException {
if (size == maxSize) {
throw new BufferFullException();
}
stack[size] = item;
size++;
System.out.println("push " + item.toString());
}
public static void main(final String[] args) {
final Scanner stdin = new Scanner(System.in);
final MyStack<Integer> stack = new MyStack<Integer>(
Integer.parseInt(args[0]));
while (stdin.hasNext()) {
final String command = stdin.next();
try {
if (command.equals("push")) {
stack.push(Integer.parseInt(stdin.next()));
} else if (command.equals("pop")) {
stack.pop();
} else {
continue;
}
} catch (final BufferFullException e) {
System.out.println("Stack is full");
} catch (final BufferEmptyException e) {
System.out.println("Stack is empty");
}
}
stdin.close();
}
}