改造接口章节的ArrayIntegerStack,为其pop()、push()、peek()方法添加出错时抛出异常的功能。
ArrayIntegerStack类内部使用数组实现。创建时,可指定内部数组大小。
属性:
int capacity;//代表内部数组的大小
int top;//代表栈顶指针。栈空时,初始值为0。
Integer[] arrStack;//用于存放元素的数组
方法:
public Integer push(Integer item); //如果item为null,则不入栈直接返回null。如果栈满,抛出FullStackException(系统已有的异常类)。
public Integer pop(); //出栈。如果栈空,抛出EmptyStackException,否则返回
public Integer peek(); //获得栈顶元素。如果栈空,抛出EmptyStackException。
裁判测试程序:
class ArrayIntegerStack implements IntegerStack{
private int capacity;
private int top=0;
private Integer[] arrStack;
/其他代码/
/你的答案,即3个方法的代码/
}
解析:采用throw进行抛出,因为FullStackException等为系统已有的异常类,可以直接进行引用,不用try—catch直接可以抛出异常。
public Integer push(Integer item) throws FullStackException {
if(this.size() >= this.arrStack.length )throw new FullStackException();;
if (item == null)
return null;
this.arrStack[this.top] = item;
this.top++;
return item;
}//如果item为null,则不入栈直接返回null。如果栈满,抛出`FullStackException`。
public Integer pop() throws EmptyStackException {
if(this.empty()) throw new EmptyStackException();
if (this.arrStack[top-1] == null)
return null;
this.top--;
return this.arrStack[top];
}//出栈。如果栈空,抛出EmptyStackException。否则返回
public Integer peek() throws EmptyStackException {
if(top == 0) throw new EmptyStackException();
if (arrStack[top-1] == null) return null;
return arrStack[top-1];
}//获得栈顶元素。如果栈空,抛出EmptyStackException。