2016-09-18 64 views
-3

想我從GUI Jtextfield如何存儲的歷史,其中已經在ArrayList中已經做

2D6存儲和使用拆分字符串,並以單獨的ArrayList保持2和6。然後檢索數字和創建的環路

for(i=2;i<=6,i++){ 
    data.add(i); //data is another arraylist 
} 

[2,3,4,5,6,7,8,9,10,11,12]  // values stored in an arraylist 

,如果我現在除去從數據2和3(ArrayList的)[4,5,6,7,8,9,10,11,12]

現在再次我使用另一個字符串「3d8」和同一過程繼續

現在,如果我再輸入數字「2d6」 怎樣記住歷史和印刷展時該值[4,5,6,7,8,9,10,11,12] ,而不是這個值

[2,3,4,5,6,7,8,9,10,11,12] 
+0

只需登錄他們... – Idos

回答

0

只是爲了在那裏你繼續做與從文本中提取兩個數字同樣的事情這個特定的程序,我可以建議你使用第三方ArrayList名爲hist存儲在每一步中對數字的。假設您要存儲n步驟的歷史記錄以便於執行重做。我將使用一個名爲History的類與數據成員一起存儲這兩個數字。

class History{ 
    int a, b; 
    History(int a, int b){ this.a=a; this.b=b; } 
} 
在你的主類

現在...

public static void main(String[] args){ 
    ArrayList<History> hist = new ArrayList<History>(n); 
    //int a,b store the two numbers from the text 
    ... 
    //adding the step to the history list 
    if(hist.size() < n) 
     hist.add(new History(a,b)); 
    else{ 
     //shift every element to the left 
     //and add new history in the end 
     //since hist's capacity = n 
    } 
} 

如果int s表示步數,然後返回hist.get(s-1)存儲該步驟的對數字的對象。這可以幫助。這是一個簡單的方法。


@Ole V.V.給出了一個很好的建議。如果您的步驟數量有限制,則更優選的方式是使用ArrayDequejava.util包中存在的ArrayDeque),因爲您不必手動輸入用於移動元素的代碼和改用類方法。在這種情況下,在main()代碼變得

ArrayDeque<History> hist = new ArrayDeque<History>(n); 
... 
//adding the pairs 

if(hist.size() == n) 
    hist.removeFirst(); 
hist.addLast(new History(a,b)); 
+1

如果你想有一個限制大小歷史扔舊的歷史了,'java.util.ArrayDeque'是完全正確的類用於那個(而不是'ArrayList')。爲您節省轉移。 –

相關問題