package dljd;
public class Stack {
Object[] elements;
int insert=0;
Stack(){
this(3);
}
Stack(int max){
elements = new Object[max];
}
public void push(Object element) throws StackException
{
if(insert==elements.length)
{
throw new StackException("栈已满了");
}
elements[insert++]=element;
}
public Object pop() throws StackException
{
if(insert==0)
{
throw new StackException("栈是空的");
}
return elements[--insert];
}
}
package dljd;
class User
{
String name;
int num;
User(String name,int num)
{
this.name=name;
this.num=num;
}
}
public class Test{
public static void main(String[] args)
{
Stack s=new Stack();
User u1=new User("A",1);
User u2=new User("B",2);
User u3=new User("C",3);
try{
s.push(u1);
s.push(u2);
s.push(u3);
}catch(StackException e)
{
e.printStackTrace();
}
try{
s.pop();
s.pop();
s.pop();
//s.pop();
}catch(StackException e)
{
e.printStackTrace();
}
}
}
package dljd;
public class StackException extends Exception{
StackException()
{
}
StackException(String m)
{
super(m);
}
}
Exception()
构造详细消息为 null 的新异常。
Exception(String message)
构造带指定详细消息的新异常。