how to generate random number from array
23,606
import java.util.Random;
...
Random random = new Random();
System.out.println(n[random.nextInt(n.length)]);
Author by
Jessy
Updated on July 09, 2022Comments
-
Jessy almost 2 years
How to generate random number from an array? and not from a range.
int n [] = {1,7,3,5,8,10,33,12,18}
-
mmmmmm almost 12 yearspossible duplicate of How to generate a random number with Java from given list of numbers
-
Anderson Green about 11 yearsIt isn't clear what this question is asking. Do you want to randomly pick a number from this array, and then return that number?
-
-
Jessy about 14 yearsThank you :-) ...you are brilliant!
-
Rich about 14 yearsNote that you should cache the
Random
instance in a field instead of creating a new instance each time you need a random number.