2017-04-01 151 views
0

嗨,大家我想實現一個圓形陣列,但有些東西不完全正確。我不確定是否在添加方法或顯示中。當你運行調試器時,數字在那裏,但我不能讓他們按順序。請你能看看並給我一個反饋。謝謝。圓形隊列陣列

public static void main (String[] args) 
{ 
    Scanner input = new Scanner (System.in); 
    Queue q1 = new Queue(); 
    int choice = 0; 

    do 
    { 
     System.out.println ("Menu:"); 
     System.out.println ("1: Add"); 
     System.out.println ("2: Remove"); 
     System.out.println ("3: Display"); 
     System.out.println ("4: Exit"); 

     System.out.print ("\nChoice: "); 
     choice = input.nextInt(); 

     switch (choice) 
     { 
      case 1: 
       System.out.print ("\nEnter a number: "); 
       int num = input.nextInt(); 
       q1.add (num); 
       break; 
      case 2: 
       q1.remove(); 
       break; 
      case 3: 
       q1.display(); 
       break; 
      case 4: 
       System.out.println ("Good Bye"); 
       break; 
      default: 
       System.out.println ("Wrong choice!"); 
       break; 
     } 

    } while (choice != 4); 


} 

}

公共類隊列 {

private final int SIZE; 
private int first; 
private int last; 
private int[] q; 

public Queue() 
{ 
    SIZE = 5; 
    q = new int[ SIZE ]; 
    first = 0; 
    last = 0; 
} 

public boolean isFull() 
{ 
    return last == SIZE; 
} 

public boolean isEmpty() 
{ 
    return last == first; 
} 

public void add (int x) 
{ 
    if ( ! isFull()) 
    { 
     q[ (first + last) % q.length ] = x; 
     last ++; 
    } else 
    { 
     System.out.println ("\nThe queue is full!"); 
    } 
} 

int remove() 
{ 
    int x = 0; 
    if ( ! isEmpty()) 
    { 
     x = q[ first ]; 
     first = (first + 1) % q.length; 
     last --; 
    } else 
    { 
     System.out.println ("The queue is empy"); 
    } 
    return x; 

} 

public void display() 
{ 
    if ( ! isEmpty()) 
    { 
     for (int i = first; i < SIZE; i ++) 
     { 
      System.out.println (q[ i ]); 
     } 


    } else 
    { 
     System.out.println ("The queue is emptry"); 
    } 
} 
+2

歡迎來到Stack Overflow!尋求調試幫助的問題(「爲什麼這個代碼不工作?」)必須在問題本身中包含所需的行爲,特定的問題或錯誤以及必要的最短代碼**。沒有明確問題陳述的問題對其他讀者無益。請參閱:[如何創建最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。 –

回答

0

它工作得很好。你能更具體地瞭解你的錯誤嗎?

+0

如果輸入:1,2,3,4,5,然後刪除1和2可以說。然後你想顯示,你會得到3,4,5。假設你想添加6和7,但是你將無法看到它們。所以如果你顯示,你仍然會得到3,4,5。不知何故,我需要從隊列後面看到6和7。 –

0

add()應只更新last。 remove()應該只更新first。 add()需要防止隊列滿,或者代碼需要使用隊列中的元素數來檢查隊列是否已滿(相對於空,因爲last == first,如果是empty或full),其中case add()需要防止隊列溢出。 add()可以返回一個代碼來指示add()是否成功(沒有溢出)或者失敗(溢出)。 add()可以選擇返回第三個代碼值,以指示隊列先前爲空,以防隊列從空變爲非空時需要執行某些特殊操作。

+0

謝謝,我會放棄它。 –