public class Stack{ //堆栈可以存储多种类型的数据元素 Object[] elements; int index;//指向栈顶元素上方的一个帧。 public Stack(){ this(5); } public Stack(int max){ elements=new Object[max]; } public void push()throws StackOperationStack//压栈 { if(index==elements.length){ throw New StackOperationStack("栈满!"); } elements[index++]; } public Object pop()throws StackOperationStack//弹栈 { if(index==0){ throw New StackOperationStack("栈空!"); }else{ return elements[--index]; } } }
异常机制:(压栈栈满,弹栈栈空)
//定义异常类 public class StackOperationStack{ public StackOperationStack(); public StackOperationStack(String msg){ super(msg); } } //定义测试类 public class TestStack{ public static void main(String [] agrs) { Stack s=new Stack(); Person p1=new Person(); Person p2=new Person(); Person p3=new Person(); Animal a1=new Animal(); Animal a2=new Animal(); } try { s.push(p1); s.push(p2); s.push(p3); s.push(a1); s.push(a2); }catch(StackOperationException e){ System.out.println("栈已满"); } try { s.pop(); s.pop(); s.pop(); s.pop(); s.pop(); }catch(StackOperationException e){ System.out.println("栈已空"); } } class person{} class Animal{}
时间: 2024-10-10 14:40:49