简体   繁体   English

集合堆栈 isEmpty 方法

[英]Collection stacks isEmpty method

learning about collection stacks, hopefully this is enough information, but essentially it keeps giving me an error.this error is also being shown when I use my pop method but showing peek should suffice.学习收集堆栈,希望这是足够的信息,但本质上它一直给我一个错误。当我使用我的 pop 方法时也会显示这个错误,但显示 peek 就足够了。 The errors are错误是

Exception in thread "main" McCracken_A06Q1$EmptyCollectionException: 
The stack is empty.

And

throw new EmptyCollectionException("stack");  

and errors where I put peek or pop methods in my main.以及我在 main.js 中放置 peek 或 pop 方法的错误。

    public T peek() throws EmptyCollectionException {
        if (isEmpty()) 
            throw new EmptyCollectionException("stack");


            return stack[top - 1];

    }

    /**
     * Returns true if this stack is empty and false otherwise.
     * 
     * @return true if this stack is empty
     */
    public boolean isEmpty() {
        if (top >0) {
            return false;
        } else {
            return true;
        }
    }

I assumed that it was my public static class EmptyCollectionException but I'm not getting any errors我认为这是我的公共静态类 EmptyCollectionException 但我没有收到任何错误

public static class EmptyCollectionException extends RuntimeException {
    /**
     * Sets up this exception with an appropriate message.
     * 
     * @param collection
     *            the name of the collection
     */
    public EmptyCollectionException(String collection) {
        super("The " + collection + " is empty.");
    }
}

EDIT: for reference.. This is my main public static void main(String[] args) { ArrayStack stack = new ArrayStack();编辑:供参考.. 这是我的主要 public static void main(String[] args) { ArrayStack stack = new ArrayStack();

    System.out.println("STACK TESTING");

    stack.push(3);
    stack.push(7);
    stack.push(4);
    System.out.println(stack.peek());
    stack.pop();
    stack.push(9);
    stack.push(8);
    System.out.println(stack.peek());
    System.out.println(stack.pop());
    System.out.println(stack.peek());
    System.out.println(stack.pop());
    System.out.println(stack.pop());
    System.out.println(stack.pop());
    System.out.println(stack.pop());

    System.out.println("The size of the stack is: " + stack.size());
    System.out.println("The stack contains:\n" + stack.toString());
}

Calling pop too many times throws an uncaught runtime exception, which terminates your program.多次调用pop会引发未捕获的运行时异常,从而终止您的程序。

Try the following code:试试下面的代码:

try {
    // Stack operations that might throw an EmptyCollectionException go here
} catch (EmptyCollectionException e) {
    e.printStackTrace();
    // Handle exception here
}

I count 5 push es and 6 pop s.我数了 5 个push es 和 6 个pop s。 Therefore your exception is valid (assuming it's on the last pop ).因此,您的异常是有效的(假设它在最后一个pop )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM