改造接口章节的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。
本文详细介绍了如何在ArrayIntegerStack类中为pop()、push()和peek()方法添加异常处理功能,确保当栈满或栈空时能正确抛出FullStackException和EmptyStackException异常。
748

被折叠的 条评论
为什么被折叠?



