随机数发生器问题

时间:2015-06-09 20:11:45

标签: java random

我的问题是下面的代码是否正确生成一个随机数,就像在过去的20次尝试中我得到500 000次5次,这并不能反映出获得它的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;
        }

1 个答案:

答案 0 :(得分:2)

我将你的代码绑在简单的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);
    }
}

当我多次运行时,它会产生大约2倍500000,相当于2%的几率(98和99)

相关问题