2014-05-06 92 views
0
public class ArrayQueue{ 
    private Object[] theArray; 
    private int currentSize; 
    private int front; 
    private int rear; 
    static final int DEFAULT_CAPACITY=10; 
    public ArrayQueue(){ 
     theArray=new Object[DEFAULT_CAPACITY]; 
     makeEmpty();  
    } 
    public void makeEmpty(){ 
     currentSize=0; 
     rear=-1; 
     front=0; 
    } 

    public void enqueue(Object x) throws OverFlow{ 
     if (isFull()) 
      throw new OverFlow("Array size exceeded"); 
     else{ 
      rear=increment(rear); 
      theArray[rear]=x; 
      currentSize++; 
      } 
     } 

    public Object dequeue()throws UnderFlow{ 
     if (isEmpty()) 
      throw new UnderFlow("Empty array"); 
     else{ 
      Object returnValue=theArray[front]; 
      theArray[front]=null;//check if this has to be done 
      front=increment(front); 
      currentSize--; 
      return returnValue; 
     } 
    } 

    public Object getFront() throws UnderFlow{ 
     if (isEmpty()) 
      throw new UnderFlow("Empty array"); 
     else 
      return theArray[front]; 

    } 

    public boolean isEmpty(){ 
     if (currentSize==0) 
      return true; 
     else 
      return false; 
    } 

    public boolean isFull(){ 
     if (currentSize==theArray.length) 
      return true; 
     else 
      return false; 
    } 

    public int increment(int x){ 
     if (x+1==currentSize) 
      x=0; 
     else 
      x++; 
     return x; 
     } 

public static void main (String args[]){ 
    ArrayQueue q=new ArrayQueue(); 
    q.enqueue("1"); 
} 


} 



public class OverFlow extends Exception{ 
    public OverFlow(){ 
     super(); 
    } 
    public OverFlow(String s){ 
     super(s); 

    } 
} 


public class UnderFlow extends Exception{ 
    public UnderFlow(){ 
     super(); 
    } 
    public UnderFlow(String s){ 
     super(s); 

    } 
} 

當我嘗試運行這個時,我得到一個錯誤,因爲未報告的異常OverFlow,必須被捕獲或聲明爲拋出。
我是新來的Java和編程,但我一定要學習數據結構course.Therefore如果有人能告訴我什麼是錯在這裏以及如何糾正它,它會是很有益的如何在隊列中使用異常

+0

什麼線是錯誤的? –

回答

2

擴展Exception(與任何類RuntimeException的例外)是considered a checked exception。這意味着程序員你必須在try...catch塊中捕獲它,或者在別處拋出異常。

問題是您的方法enqueue()引發檢查的異常。

你可以解決這一個的方法有兩種:

  • 包裹在try...catch塊調用enqueue,或者
  • 添加throws OverFlowmain

兩個例子:

try { 
    q.enqueue("1"); 
} catch (OverFlow e) { 
    e.printStackTrace(); 
} 


public static void main(String[] args) throws OverFlow { 
    ArrayQueue q=new ArrayQueue(); 
    q.enqueue("1"); 
} 
+0

+1,我最好是這個的複製 – drewmoore

+0

謝謝我作出更改爲'公共靜態無效main(String args [])拋出溢出,UnderFlow {'。它的工作。我想我將不得不學習更多例外 –

+0

嗯,只是因爲*工作*並不一定意味着它*正確*做到這一點。這是你的兩個選擇,你通常不想在'main'中引發異常。當你使用一個檢查過的異常時,這個想法是程序應該能夠相對簡單地從異常中恢復。另一種形式(用'try ... catch'包裝)可能是更好的方法。 – Makoto