2013-10-27 64 views
0

我遇到問題。代碼:隊列有什麼問題?

// withdraw method 
public void withdraw(long n) 
{ 
    this.n = n; 
    Action a = new WithDraw(); 
    a.doAction(n); 
    **if(actionsList.size() > 10)** 
    { 
     actionsList.poll(); 
     actionsList.offer(a); 

    } else 
    { 
     actionsList.offer(a); 
    } 

} 

// Deposit method goes here 

    public void deposit(long n) 
{ 
    this.n = n; 
    Action a = new Deposit(); 
    a.doAction(n); 
    **if(actionsList.size()<10)** 
    { 

     actionsList.offer(a); 
    } else 
    { 
     actionsList.poll(); 
     actionsList.offer(a); 
    } 

} 

的主要功能如下:

acc1.deposit(1); 
    acc1.withdraw(2); 
    acc1.deposit(3); 
    acc1.withdraw(4); 
    acc1.deposit(5); 
    acc1.withdraw(6); 
    acc1.deposit(7); 
    acc1.withdraw(8); 
    acc1.deposit(9); 
    acc1.withdraw(10); 
    acc1.deposit(11); 
    acc1.withdraw(12); 
    acc1.deposit(13); 
    acc1.withdraw(14); 
    acc1.deposit(15); 
    acc1.displayActions(); 

我需要10最後添加的元素。在這之後,我得到了11個元素而不是10個。這是什麼問題?也許我不明白Queue size()是否正確?

ADDED打印方法:

public void displayActions() 
    { 
     for(Action s : actionsList) 
     { 
      System.out.println(s); 
     } 
    } 
+0

請發表您的'displayActions'方法。 –

+0

這就是我所理解的(這是否正確?):您有兩種行爲:撤回和存款。這些行爲從銀行賬戶中提取或存入資金等某些地方。所有這些行爲都會排成一隊,只有最後十個人應該呆在那裏 - 無論是退出還是存款。我第一個不明白的是不對稱的代碼。隊列方面,他們也是這樣做的,應該有相同的代碼 - 或者我誤解了?你能解釋一下嗎? – jboi

+0

首先,你理解正確。其次,這是否是對稱的並不重要,因爲我固定它使其對稱,但結果是相同的。 – Ernusc

回答

2

當大小等於10,你還可以添加其他,所以你得到11

正如其他人所說的>相反的是<=>=<==!=總之,你應該儘量保持你的代碼儘可能一致。如果代碼應該做同樣的事情,你應該以同樣的方式寫出來,如果不使用一種方法來執行它們。

public void withdraw(long n) { 
    queueAction(new Withdrawal(n)); 
} 

public void deposit(long n) { 
    queueAction(new Deposit(n)); 
} 

void queueAction(Action action) { 
    action.doAction(); 
    if (actionsList.size() >= 10) 
     actionsList.poll(); 
    actionsList.offer(aaction); 
} 

我已經採取了this.n = n;因爲這似乎並沒有做任何事情,我沒有看到你排隊之前,執行操作的點...

我不知道爲什麼我會想要默默地放棄比過去10年更久的任何存款。我希望能夠忽略我的一些提款。

+0

尼斯解決方案,謝謝。 – Ernusc

1

這只是不是從0開始的.size()的一個簡單的例子?

IE,0,1,2,3,4,5,6,7,8,9,10 = 11

+0

我不這麼認爲,但我也不確定,究竟需要達到什麼。如果你詢問size()<10',隊列最多有10個元素。元素索引0-9,但我沒有看到那裏的代碼索引 – jboi

0

withdraw您測試size() > 10depositsize()<10 - 但< 10相反是不是> 10,但> = 10