我写了个堆栈基本操作的代码,但是在异常处理这里一直出问题,不知道怎么解决?

import java.util.EmptyStackException;
import java.util.Stack;

public class ArrayStack<E> implements TestStack<E>{

    private E[] theArray;
    private int topOfStack;

    public static final int DEFAULT_CAPACITY = 20;

    public ArrayStack(){

        theArray = (E[])new Object[DEFAULT_CAPACITY];
        topOfStack = -1;

    }
    //overwrite the push meathod
    public void push(E data){
        if (topOfStack == theArray.length-1);
        {
            doubleArray();
        }
        topOfStack++;
        theArray[topOfStack]=data;

    }

    @Override
    public E pop() throws EmptyStackException {
        if(empty()){
            throw new EmptyStackException("Stack pop");

        }
        E result = theArray[topOfStack];
        topOfStack--;
        return result;
    }

    @Override
    public E peek() throws EmptyStackException {
        if (empty()){
            throw new EmptyStackException("Stack peek");
        }
        return theArray[topOfStack];
    }

    @Override
    public boolean empty() {
        return topOfStack == -1;
    }

    @Override
    public int size() {
        return topOfStack + 1;
    }


    private void doubleArray(){
        E[] temp =theArray;
        theArray = (E[]) new Object[temp.length*2];

        for(int i=0; i<temp.length;i++){
            theArray[i]=temp[i];
        }

    }



}

throw new EmptyStackException("Stack peek")这里和上面..(“Stack pop") 都在报错,错误显示是EmptyStackException() in EmptyStackException cannot be applied to..后面就没了,这个就很奇怪了。我也不知道错误是什么,图片描述

阅读 4k
3 个回答

两个错误:
1 pop 或者 peek 之前你应该先 push 数据
2 EmptyStackException 没有带 String 的构造函数,throw new EmptyStackException("Stack peek");throw new EmptyStackException("Stack pop"); 都应该改成 throw new EmptyStackException();

你应该没有往里面放东西

类EmptyStackException 的定义是这样的:

public
class EmptyStackException extends RuntimeException {
    private static final long serialVersionUID = 5084686378493302095L;

    /**
     * Constructs a new <code>EmptyStackException</code> with <tt>null</tt>
     * as its error message string.
     */
    public EmptyStackException() {
    }
}

没有接受字符串为参数的构造函数,所以不能new的时候加字符串参数。

推荐问题