异常在栈中的应用

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 @   晚生小白  阅读(34)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示