2013-04-24 111 views
0

我有新的數組列表,1個數組列表,其中有10個客戶已插入。我正在運行一個循環,從arraylist中挑選一個隨機客戶,並將其添加到第二個數組列表中。但是,當我將客戶插入第二個數組列表時,我會得到重複的數據。所以當循環運行後,將客戶添加到第二個數組列表中時,它將從第一個數組列表中移除它。刪除數組元素時出錯

但是,當它運行時我得到一個錯誤:Intervals error: java.lang.IndexOutOfBoundsException: Index: 7, Size: 7

ArrayList<String> customer = new ArrayList<String>(Arrays.asList(list)); 

int customerlist = customer.size(); 

while (line.isEmpty()) 
     { 
      for (int x = 0; x < customerlist; x++) 
      { 
       try 
       { 
        Thread.sleep(intervals * 1000); //Sleep method to hold the arrival time by 1-2 seconds. 
        int cus = (int) (Math.random() * customerlist); //Random customer is picked here. 
        String new_cus = customer.get(cus); //New customer object is created ere. 
        line.add(new_cus); //Customer objects are added to the empty LinkedList queue. 
        customer.remove(cus); 

        //For loop statement to outputting the queue. 
        for (String s : line) 
        { 
         System.out.print("[" + s.toString() + " " + "]"); //Outputting each customer and using the ".name" method so customers are readable. 
        } 
        //Outputting the whole queue and stating who has joined the queue. 
        System.out.println("\n" + "The queue has " + line.size() + " customers so far" + "\n" + 
        new_cus.toString() + " Has Joined the Queue " + " <=== WAITING" + "\n"); 
       } 
       catch(Exception e) //ERROR handler for sleep method. 
       { 
        System.out.println("Intervals error: " + e); //Outputting the ERROR message. 
        System.exit(0); //If ERROR found exit system. 
       } 

      } 
     } 
+0

試着鋪設'cus'的價值。 – Bucket 2013-04-24 16:22:39

+0

你只是試圖把給定的客戶按隨機順序放入列表中? – 2013-04-24 16:25:17

+0

基本上我試圖刪除重複的客戶被添加到我的第二個arraylist,但我需要客戶被隨機挑選出來。 – user1898552 2013-04-24 16:30:33

回答

1

你從數組刪除您可以有效地迭代,尚未相應地更新狀態。

變化:

for (int x = 0; x < customerlist; x++) 

for (int x = 0; x < customer.size(); x++) 

(或者更好的是,使用迭代器在基本ArrayList,這樣就可以使用Iterator.remove()功能安全地刪除。)

而且換行:

int cus = (int) (Math.random() * customerlist); 

int cus = (int) (Math.random() * customer.size()); 
+0

我不明白你能解釋一下嗎。 – user1898552 2013-04-24 16:23:29

+0

Oki im沒有得到一個錯誤,但我需要10客戶添加到第二arraylist與代碼你給我它只能添加5個客戶。它工作得到10個客戶,我只是改變了循環值我<10;謝謝 – user1898552 2013-04-24 16:32:34

1

這就是問題所在:

int cus = (int) (Math.random() * customerlist); 

這很好(雖然不是乾淨呼籲Random.nextInt)對於第一次迭代 - 但事後,customer.size()已經改變(如元素具有已被刪除)但customerlist仍然是一樣的。因此,在下一次迭代中,您正在挑選錯誤範圍內的元素。

說實話,你最好用Collections.shuffle()來改變原來的清單 - 這就是你想要的結果,對吧?

1

添加

customerlist--; 

customer.remove(cus); 

也,你可以改變

for (int x = 0; x < customerlist; x++) 

通過

for (int x = 0; x < customer.size(); x++) 

但我認爲在每個循環中調用.size函數會使用比局部變量更多的資源。

+0

這使得它的工作,但我不明白這是什麼意思customerlist--; – user1898552 2013-04-24 16:37:17

+0

這意味着customerlist = customerlist - 1; – Pol0nium 2013-04-24 16:37:45

+0

感謝每一個我明白我做錯了它基本上是每次循環運行時的customer.size()我需要用我的前面的代碼記錄數組列表的長度,這個數值是10甚至是doe我不斷從中刪除客戶。我的錯 !!!大聲笑得到ti工作再次感謝 – user1898552 2013-04-24 16:44:53