异常在栈中的应用

package myStack;
//栈异常:自定义栈
public class StackException extends Exception{
    public StackException(){
    }
    public StackException(String s){
        super(s);
    }
}

 

public class Stack {
    private int[]stack;// 对象数组
    public int top=-1;// 默认栈顶元素位置,
    public int MAX_SIZE=50;
    public Stack(){
        this.stack=new int[MAX_SIZE];
    }
    public Stack(int size)throws StackException{
        if (size<=0){
            throw new StackException("栈深至少为1");
        }else {
            /*this.stack=new int[size];*/
            // 方便后期栈置空
            MAX_SIZE=size;
            this.stack=new int[MAX_SIZE];
        }
    }
    // 置空
    public void clear(){
        top=-1;
        stack=new int[MAX_SIZE];
    }
    // 判空
    public boolean isEmpty(){
        return top==-1;
    }
    // 求栈深
    public int length(){
        return top+1;
    }
    // 压栈
    public void push(int num) throws StackException{
        if (top+1==MAX_SIZE){
            throw new StackException("栈满,无法压栈!");
        }else {
            stack[++top]=num;
        }
    }
    // 弹栈
    public int pop() throws StackException{
        if (isEmpty()){
            throw new StackException("空栈,无法弹栈");
        }
        return stack[top--];
    }
}
package myStack;

// 自定义异常在栈中的应用
public class MyStackTest {
    public static void main(String[] args) {
        Stack s = null;
        try {
            s=new Stack(10);
        }catch (StackException e){
            System.out.println(e.getMessage());
        }
        System.out.println(s.isEmpty());// true
        System.out.println(s.length());// 0
        // 弹栈
        try {
            s.pop();
        } catch (StackException e) {
            System.out.println(e.getMessage());
        }
        // 压栈测试
        for (int i=0;i<11;i++){
            try {
                s.push(i);
            } catch (StackException e) {
                System.out.println(e.getMessage());
            }
        }
    }
}
posted @ 2022-07-22 21:49  晚生小白  阅读(41)  评论(0)    收藏  举报