1

I'm having trouble doing the following and have no idea how to do it: I would like to fill an array generated with random numbers (1-40) and also make it so that the number doesn't repeat. Also, is there a way to make the array go to the next value on its own using. So let say I have test [1] = "3" and then test [2] = "6". Is there anyway to make it go to the next value instead of calling test [2]?

Thanks a lot

2

1 Answer 1

8
List<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < 40;)
{
    int rand = ((int)(Math.random() * 40)) + 1;
    if(!list.contains(rand))
    {
        list.add(rand);
        i++;
    }
}

or:

List<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < 40; i++) list.add(i);
Collections.shuffle(list);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.