3

How to generate random number from an array? and not from a range.

int n [] = {1,7,3,5,8,10,33,12,18}
2

2 Answers 2

16
import java.util.Random;

...

Random random = new Random();
System.out.println(n[random.nextInt(n.length)]);
Sign up to request clarification or add additional context in comments.

1 Comment

Note that you should cache the Random instance in a field instead of creating a new instance each time you need a random number.
0

In general terms, get a random integer ranging from a minimum of 0 to a maximum of the array length -1, and use that as the array index.

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.