本文介绍了除了生成某些值随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要生成随机数,但不希望他们从 excludeRows 阵列。这里是我的code。

 公众诠释generateRandom(INT开始,诠释年底,ArrayList的<整数GT; excludeRows){
    随机兰特=新的随机();
    INT范围=结束 - 开始+1 - excludeRows.size();
    INT无规= rand.nextInt(范围)+1;    的for(int i = 0; I< exclude.size();我++){
        如果(excludeRows.get(I)GT;随机){
            返回随机;
        }
      随机++;
    }    返回随机;
}

我用这个函数在while循环,并在每次迭代期间我添加了一个新值 excludeRows
有时,它会返回属于 excludeRows 号码。有什么问题?


解决方案

 如果(!exclude.contains(随机))
    返回随机;

试试这个每次都将返回不排除值。

I want to generate random numbers, but don't want them to be from excludeRows array. Here is my code.

public int generateRandom(int start, int end, ArrayList<Integer> excludeRows) {
    Random rand = new Random();
    int range = end - start +1 - excludeRows.size();
    int random = rand.nextInt(range) + 1;

    for(int i = 0; i < exclude.size(); i++) {
        if(excludeRows.get(i) > random) {
            return random;
        }
      random++;
    }

    return random;
}

I use this function in a while loop, and during each iteration I add a new value to excludeRows.Sometimes it returns numbers that belong to excludeRows. What's the problem?

解决方案
if(!exclude.contains(random))
    return random;

Try this every time it will return the value that is not in exclude.

这篇关于除了生成某些值随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 18:56