定義棧接口,並採用數組實現,並採用自定義異常處理棧滿和棧空時的錯誤操作。
(1)定義接口
(2)定義異常類
(3)採用數組實現棧類
實現代碼:
package CurriculumDesign;
class StackException extends Exception
{
int index = 0;
public StackException(int index) {
this.index = index;
}
@Override
public String toString() {
return "StackExceptionAt{ " + "index=" + index + " }";
}
}
interface MyStack
{
int pop() throws StackException;
void push(int value) throws StackException;
}
class ArrayStack implements MyStack
{
int pos;
int[] data = null;
public ArrayStack() {
pos = -1;
data = new int[32];
}
public ArrayStack(int size) {
pos = -1;
data = new int[size];
}
@Override
public int pop() throws StackException {
if(pos<0)
{
throw new StackException(pos);
}
return data[pos--];
}
@Override
public void push(int value) throws StackException {
if (pos >= (data.length-1))
{
throw new StackException(pos+1);
}
data[++pos] = value;
}
}
public class Test5 {
public static void main(String[] args) {
ArrayStack arrayStack = new ArrayStack(3);
try {
arrayStack.pop();
} catch (StackException e) {
System.out.println(e.toString());
}
try {
arrayStack.push(1);
System.out.println("棧頂壓棧的值爲:1");
arrayStack.push(2);
System.out.println("棧頂壓棧的值爲:2");
arrayStack.push(3);
System.out.println("棧頂壓棧的值爲:3");
arrayStack.push(4);
System.out.println("棧頂壓棧的值爲:4");
} catch (StackException e) {
System.out.println(e.toString());
}
try {
System.out.println("取出棧頂元素的值爲:"+arrayStack.pop());
System.out.println("取出棧頂元素的值爲:"+arrayStack.pop());
System.out.println("取出棧頂元素的值爲:"+arrayStack.pop());
System.out.println("取出棧頂元素的值爲:"+arrayStack.pop());
} catch (StackException e) {
System.out.println(e.toString());
}
}
}
運行結果: