开发者

how to generate random number from array

开发者 https://www.devze.com 2022-12-25 00:32 出处:网络
How to generate random number from an array? and not from a range. int n [] = {1,7,3,5,8,10,33开发者_开发问答,12,18}

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

int n [] = {1,7,3,5,8,10,33开发者_开发问答,12,18}


import java.util.Random;

...

Random random = new Random();
System.out.println(n[random.nextInt(n.length)]);


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号