ArrayList用随机数填充,奇怪地导致foreach从随机索引中绘制

时间:2013-12-13 13:50:30

标签: java random arraylist indexoutofboundsexception

我还是Java的新手,最近开始尝试使用ArrayList和LinkedList。编程简单的彩票算法时,我遇到了一个我不太了解的问题。

这是我的代码:

import java.util.*;

public class Millionaire 
{
    public static void main(String[] args) 
    {
        ArrayList<Integer> lottery = new ArrayList<Integer>();
        Random draw = new Random();

        for (int i = 0; i < 6; i++) 
        {
            lottery.add(draw.nextInt(50));
        }

        for (int m : lottery)
        {
            System.out.println(lottery.get(m));
        }
    }
}

编译顺利进行,但运行该程序几乎总是会导致OutOfBoundsExeption。似乎打印循环尝试使用Arraylist的内容作为它尝试访问的索引,因此任何大于6的条目都会导致程序崩溃。任何人都可以帮助我理解为什么会这样做吗?

5 个答案:

答案 0 :(得分:4)

基本上,m 是彩票号码,而不是索引。所以如果你的ArrayList是:

30,11,2,4,8,17

然后你的for循环首先获取第一个值(30),并尝试在索引30处获得抽奖值(导致你的异常)。

您只需更改第二个for循环即可:

System.out.println(m);

或者,如果要获取索引m处的值,则应将for循环更改为以下内容:

int c = lottery.size();

for(int i = 0; i < c; i++) {
    System.out.println(lottery.get(i));
}

答案 1 :(得分:1)

请记住: m你的循环是ArrayList<Integer>中的值,它不是列表ArrayList<Integer>的索引。 m范围[0,50]。您正在尝试生成6个int随机数,如果随机数生成大于6,那么,使用这样的随机数,将导致异常: OutOfBoundsExeption ,您的for循环如下:

    for (int m : lottery)
    {
        System.out.println(lottery.get(m));
    }

有两种方法可以避免异常。

<强>路#1:

更改

    for (int m : lottery)
    {
        System.out.println(lottery.get(m));
    }

    for (int m : lottery)
    {
        System.out.println(m);
    }

<强>路#2

更改

    for (int m : lottery)
    {
        System.out.println(lottery.get(m));
    }

    for(int i=0; i < lottery.size();i++)
    {
        System.out.println(lottery.get(i));
    }

答案 2 :(得分:0)

那是因为for for循环

for (int m : lottery) 

迭代lottery数组的值。所以m有6个随机值。您假设m将是索引值。

答案 3 :(得分:0)

试试这个:

public static void main(String[] args) {
    ArrayList<Integer> lottery = new ArrayList<Integer>();
    Random draw = new Random();

    for (int i = 0; i < 6; i++) {
        lottery.add(draw.nextInt(50));
        System.out.println(lottery.get(i));
    }

答案 4 :(得分:0)

在你的上一个循环中,你已经有了随机整数m。你不需要去lottery.get(...)部分。