自写栈空异常—Java

自写异常类:
/**

  •  自写栈空异常类
    

*/
public class EmptyException extends Exception {
public EmptyException() {
}

public EmptyException(String message) {
    super(message);
}

}

数组模拟栈:

import java.util.Arrays;

/**

  • 数组模拟栈——后进先出表
    */
    public class Stack {
    private int top = -1 ;//栈顶前一个位置
    private int maxSize;
    private int[] arr;

    public Stack(int maxSize) {
    this.maxSize = maxSize;
    arr = new int[maxSize];
    }

    public void setArr(int[] arr) {
    this.arr = arr;
    }

    public boolean isFull(){//判断栈满
    return topmaxSize - 1;//返回top等于maxSize-1
    }
    public boolean isEmpty() throws EmptyException {//判断栈空
    if(top
    -1) {//如果top等于-1
    throw new EmptyException(“栈空异常!”);
    }
    else return false;
    }
    public void push(int count){//入栈

     if(!isFull()){
         top++;
        arr[top]=count;
     }else System.out.println("栈满,不能再添加元素");
    

    }
    public void pop() throws EmptyException {//出栈

         if (!isEmpty()) {
             System.out.println("出栈元素:"+arr[top]);
             arr[top] = 0;
             top--;
    
         }
    

    }
    public void peek() throws EmptyException {//显示栈顶元素
    if(!isEmpty()) {
    System.out.println(“栈顶元素:” + arr[top]);
    }
    }
    public void show() throws EmptyException {
    if (!isEmpty()) {
    int temp = top;//临时辅助指针
    for (int i = temp; i >= 0; i–) {
    System.out.printf(“stack[%d] = %d\n”, i, arr[i]);
    }
    }
    }
    }

测试类:

/**

  • 测试类
    */
    public class Test {
    public static void main(String[] args) throws EmptyException {
    Stack stack = new Stack(10);
    while(true){
    System.out.println(“请输入指令:in(入栈)/out(出栈)/check(查栈顶元素)/show(显示栈)/exit(退出)/”);
    Scanner sca= new Scanner(System.in);
    String str = sca.next();
    if(str.equals(“in”)){
    System.out.println(“请输入入栈元素:”);
    int count = sca.nextInt();
    stack.push(count);
    }else if(str.equalsIgnoreCase(“out”)){
    try {
    stack.pop();
    }catch(Exception e){
    e.printStackTrace();
    }
    }else if(str.equalsIgnoreCase(“check”)){
    try {
    stack.peek();
    } catch (EmptyException e) {
    e.printStackTrace();
    }
    }else if(str.equalsIgnoreCase(“exit”)){
    System.out.println(“再见!”);
    break;
    }else if(str.equalsIgnoreCase(“show”)){
    stack.show();
    }
    else System.out.println(“输入有误,请重输”);

    }
    

    }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值