50,532
社区成员
发帖
与我相关
我的任务
分享
import java.lang.Object;
import java.util.Vector;
class EmptyStackException extends Exception {
public EmptyStackException(String message) {
super(message);
}
}
class FullStackException extends Exception {
public FullStackException(String message) {
super(message);
}
}
public class MyStack<T> {
Vector<T> vec = new Vector<T>();
public MyStack() {
int MyStackSize = 5;
};
public void push(T item) throws FullStackException {
if (vec.size() >= 5) {
throw new FullStackException("堆栈满,不可再进行压入。");
} else {
vec.add(item);
}
}
public void pop(T item) throws EmptyStackException {
if (vec.size() == 0) {
throw new EmptyStackException("堆栈空,不可再进行删除。");
} else {
vec.remove(item);
}
}
public boolean isEmpty() {
if (vec.size() == 0)
return true;
else
return false;
}
public boolean isFull() {
if (vec.size() == 5)
return true;
else
return false;
}
public void display() {
for (int i = 0; i < vec.size(); i++) {
System.out.print(vec.get(i) + " ");
}
System.out.println();
}
}
class TestMyStack {
public static void main(String[] args) {
MyStack<Integer> s = new MyStack<Integer>();
int i = 0;
try {
while (!s.isFull()) {
s.push(i);
i++;
}
s.display();
s.push(5); // 异常
while (!s.isEmpty()) {
s.pop(5);
}
s.pop(5); // 异常
} catch (FullStackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (EmptyStackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}