作者 郑如滨
单位 集美大学
改造接口章节的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。
思考:
使用异常而不是通过返回null来提示用户程序出错有什么好处?
裁判测试程序:
class ArrayIntegerStack implements IntegerStack{ private int capacity; private int top=0; private Integer[] arrStack; /*其他代码*/ /*你的答案,即3个方法的代码*/ }
public Integer push(Integer item){
if(item == null)
return null;
if(top >= capacity){
throw new FullStackException();
}
arrStack[top++] = item;
return item;
}
public Integer pop(){
if(top == 0){
throw new EmptyStackException();
}
return arrStack[--top];
}
public Integer peek(){
if(top == 0){
throw new EmptyStackException();
}
return arrStack[top - 1];
}