测试类:
class Test {
public static void main(String[] args) throws StackOperationException{
Stack st = new Stack();
try {
st.push(new User("hl",1));
st.push(new User("hf",2));
st.push(new User("yx",3));
st.push(new User("hx",4));
st.push(new User("ll",5));
}catch(Exception e) {
e.printStackTrace();
}
try {
System.out.println(st.pop());
System.out.println(st.pop());
System.out.println(st.pop());
System.out.println(st.pop());
System.out.println(st.pop());
}catch(Exception e) {
e.printStackTrace();
}
}
}
栈类:
class Stack{
Object[] elements;
int index;
Stack(){
this(5);
}
Stack(int max){
elements = new Object[max];
}
public void push(Object element) throws StackOperationException {
if(index == elements.length) {
throw new StackOperationException("越栈");
}
else {
elements[index++] = element;
}
}
public Object pop() throws StackOperationException {
if(index == 0) {
throw new StackOperationException("栈空");
}
else {
Object element = elements[--index];
return element;
}
}
}
自定义异常:
class StackOperationException extends Exception{
public StackOperationException() {}
public StackOperationException(String msg) {
super (msg);
}
}
添加用户类:
class User{
String name;
int age;
User(String name,int age){
this.name = name;
this.age = age;
}
public String toString() {
return name + " " + age;
}
}
网友评论