I have 2 classes, a test class and a regular class. The regular class has the methods object peek(), object push(), and object pop(). For the peek and the pop methods I am using an EmptyStackException. For some reason, the EmptyStackException will not allow me to enter in parameters for it like my exception for the push method does. Therefore, when I put it in the test class and my stack is empty, it doesn't check the exception. This part of my class looks like this:
Expand|Select|Wrap|Line Numbers
- public Object peek() // Returns object on top of this stack without removing it from the stack. Throws an EmptyStackException if this stack is empty
- {
- if( top == -1 )
- {
- throw new EmptyStackException();
- }
- return stk[top];
- }
- public Object pop() // Removes and returns object at top of this stack. Throws an EmptyStackException if the stack is empty
- {
- if( top == -1 )
- {
- throw new EmptyStackException();
- }
- return stk[top--];
- }
Expand|Select|Wrap|Line Numbers
- try
- {
- System.out.println(newStack.push("tart"));
- System.out.println(newStack.push("chocolate"));
- System.out.println(newStack.pop());
- System.out.println(newStack.pop());
- System.out.println(newStack.pop());
- }
- catch(EmptyStackException emptyEmpty)
- {
- System.out.println("Stack is empty - could not carry out operation");
- }
tart
chocolate
chocolate
tart
null
Could somebody please tell me if they see something wrong in my coding, and perhaps lead me to a solution? Thank you so much!