Probability in Java

前端 未结 5 698
借酒劲吻你
借酒劲吻你 2020-12-04 21:57

I was curious to know, how do I implement probability in Java? For example, if the chances of a variable showing is 1/25, then how would I implement that? Or any other proba

5条回答
  •  醉梦人生
    2020-12-04 22:03

    Java has a class called java.util.Random which can generate random numbers. If you want something to happen with probability 1/25, simply generate a random number between 1 and 25 (or 0 and 24 inclusive) and check whether that number is equal to 1.

    if(new java.util.Random().nextInt(25)==0){
        //Do something.
    }
    

提交回复
热议问题