随机数生成器问题

Random number generator problems

我的问题是下面的代码是否正确地生成了一个随机数,因为在过去的 20 次尝试中我得到了 5 次 500 000,这根本没有反映出获得它的 2% 的机会......

  public static int randInt(int min, int max) {

        // NOTE: Usually this should be a field rather than a method
        // variable so that it is not re-seeded every call.
        Random rand = new Random();

        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        int randomNum = rand.nextInt((max - min) + 1) + min;

        return randomNum;
    }

    public void prizegenerator(View v) {
        int fate = randInt(0,100);
        int reward=0;
        if (fate <= 30) {
            reward = 1000;
        }
        else if (fate <= 50) {
            reward = 2000;
        }
        else if (fate <= 80) {
            reward = 5000;
        }
        else if (fate <=90) {
            reward =  10000;
        }
        else if (fate <= 95) {
            reward = 50000;
        }
        else if (fate <= 97) {
            reward = 100000;
        }
        else if (fate <= 99) {
            reward = 500000;
        }
        else if (fate <= 100) {
            reward = 1000000;
        }

我将您的代码绑定到简单的 main 方法中并且工作正常。亲自尝试一下:

public static void main(String[] args) {
    Main main = new Main();
    List<Integer> list = new ArrayList<Integer>();
    for (int i = 0; i < 100; i++) {
        list.add(main.prizegenerator());
    }
    Collections.sort(list);

    for (Integer integer : list) {
        System.out.println(integer);
    }
}

当我 运行 它多次时,它生成的次数主要是 500000 的 2 倍,这与你的 2% 几率(对于 98 和 99)相匹配