Java實戰(五)用數組實現棧(自定義異常、接口)

定義棧接口,並採用數組實現,並採用自定義異常處理棧滿和棧空時的錯誤操作。

(1)定義接口
(2)定義異常類
(3)採用數組實現棧類

實現代碼:

package CurriculumDesign;

/*
 4.定義棧接口,並採用數組實現,並採用自定義異常處理棧滿和棧空時的錯誤操作。
 (1)定義接口
 (2)定義異常類
 (3)採用數組實現棧類
*/

//自定義異常類,繼承Exception類
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) {
     //定義一個長度大小爲3的棧
     ArrayStack arrayStack = new ArrayStack(3);

     //此時隊列爲空,取出元素會產生異常
     try {
         arrayStack.pop();
     } catch (StackException e) {
         System.out.println(e.toString());
     }

     //此時加入插入四個元素(>3)隊列會產生異常
     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());
     }
 }
}

運行結果:

在這裏插入圖片描述

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章