问题描述
我想问一下如何在java中生成一个随机数,我知道它是由random.nextint()完成的,但是我想检查该数字是否不是我想要的,然后应该拒绝它,并应该生成一个新的随机数。
我想要这样的东西:
Integer[] in = {1,2,3,4,5};
int a = new Random().nextInt(10);
for(int i=0;i<in.length ;i++)
if(a==in[i])
//new random number
如果上面的数组中存在数字,则应生成新的随机数
1楼
只需将其放入do-while循环中即可:
int a;
do {
a = new Random().nextInt(10);
} while (Arrays.asList(in).contains(a));
2楼
我会避免一开始就不生成您不想要的数字。
你可以做
int a = random.nextInt(5);
if (a > 0) a += 5;
或使用选择
int[] valid = { 0, 6, 7, 8, 9 }; // 0 to 9 but not 1,2,3,4,5
int a = valid[random.nextInt(valid.length)];
3楼
只需再次调用该方法。 也就是说,如果生成的数字符合if条件,则调用a = new Random()。nextInt(10);
或者,如果您的for循环曾经重新生成随机数,则可以让if语句不执行任何操作:if(xyz){}; 当然,这毫无意义,我认为最初的解决方案可能就是您所追求的。
4楼
为了避免任何循环和重试,请尝试以下操作:
int [] in = {1,2,3,4,5};
// generate integers from 0 up to the size of your array of allowed numbers:
int index = new Random().nextInt(in.length);
int a = in[index]; // use the random integer as index for your array of allowed numbers