随机数存储在数组列表中并从中进行选择

时间:2013-04-24 06:58:06

标签: java arrays random arraylist

我正在尝试创建一个程序来生成随机数并存储到arraylist。 同时将存储的号码设为multiply

我已经存储了生成的数字,但我如何实际得到我想要的数字。 对于这个例子,我试图得到3rd number,我错过了哪一步?

public class arraylist {

    public static void main(String[] args) {

        List<Integer> list = new ArrayList<Integer>();
        Random rand = new Random();

        int numtogen;
        int third;
        Scanner scan = new Scanner(System.in);
        System.out.println("How many number do you want to generate: ");
        numtogen = scan.nextInt();
        System.out.println("What number do you want to multiply with the third number: ");
        third = scan.nextInt();

        HashSet<Integer> generated = new HashSet<Integer>();

        // Prevent repeat
        for (int x = 1; x <= numtogen; ++x) {
            while (true) {
                // generate a range from 0-100
                int ranNum = rand.nextInt(100);

                if (generated.contains(ranNum)) {

                    continue;
                } else {
                    list.add(ranNum);
                    System.out.println("Number " + x + "=" + " = " + ranNum);
                    break;
                }

            }

        }
        int numinlist;
        while (!list.isEmpty()) {

            // Integer[] numlist= numbinlist.hasNextInt;

            // int answer = numlist[2]*third;
            // System.out.println("Answer to first number  = "+answer);
        }
    }

}

3 个答案:

答案 0 :(得分:3)

您可以将非重复数字的生成更改为:

Set<Integer> generated = new LinkedHashSet<Integer>();
// Prevent repeat
while (generated.size() < numtogen) {
    generated.add(rand.nextInt(100));
}
List<Integer> list = new ArrayList<Integer>(generated);

一旦我理解了你的实际问题并且知道了答案,我就会编辑这个答案。

答案 1 :(得分:3)

如果您想获得第3个生成的数字,请尝试:

int number = list.get(2);

答案 2 :(得分:1)

改变这个:

for (int x = 1; x <= numtogen; ++x) {
    while (true) {
        // generate a range from 0-100
        int ranNum = rand.nextInt(100);

        if (generated.contains(ranNum)) {

            continue;
        } else {
            list.add(ranNum);
            System.out.println("Number " + x + "=" + " = " + ranNum);
            break;
        }
     }
 }

为:

for (int x = 1; x <= numtogen; ++x) {
    // generate a range from 0-100
    int ranNum = rand.nextInt(100);
    if (generated.contains(ranNum)) {
        continue;
    } else {
        list.add(ranNum);
        System.out.println("Number " + x + "=" + " = " + ranNum);
    }
}

然后,您需要做的就是访问第三个数字:

int answer = (list.get(2) * third);