2013-04-24 118 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