0

我有新的数组列表,1 个数组列表,其中已经插入了 10 个客户。我正在运行一个循环,它从数组列表中选择一个随机客户并将其添加到第二个数组列表中。但是,当我将客户插入第二个数组列表时,我得到了重复。因此,当循环在将客户添加到第二个数组列表后运行时,它会将其从第一个数组列表中删除。

但是,当它运行时出现错误: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.
                }

            }
        }
4

3 回答 3

1

添加

customerlist--;

customer.remove(cus);

另外,你可以改变

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

经过

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

但我认为.size在每个循环中调用函数比局部变量使用更多的资源。

于 2013-04-24T16:23:54.347 回答
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());
于 2013-04-24T16:22:36.317 回答
1

这就是问题:

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

第一次迭代很好(虽然不如调用干净Random.nextInt) - 但之后,customer.size()已经改变(因为元素已被删除)但customerlist仍然是一样的。因此,在下一次迭代中,您选择了错误范围内的元素。

老实说,您最好只使用Collections.shuffle()shuffle 原始列表 - 这就是您最终想要的结果,对吧?

于 2013-04-24T16:22:57.940 回答