Java: do something x percent of the time

前端 未结 8 865
再見小時候
再見小時候 2020-12-09 17:04

I need a few lines of Java code that run a command x percent of the time at random.

psuedocode:

boolean x = true 10% of cases.

if(x){
  System.out.p         


        
8条回答
  •  -上瘾入骨i
    2020-12-09 17:27

    You just need something like this:

    Random rand = new Random();
    
    if (rand.nextInt(10) == 0) {
        System.out.println("you got lucky");
    }
    

    Here's a full example that measures it:

    import java.util.Random;
    
    public class Rand10 {
        public static void main(String[] args) {
            Random rand = new Random();
            int lucky = 0;
            for (int i = 0; i < 1000000; i++) {
                if (rand.nextInt(10) == 0) {
                    lucky++;
                }
            }
            System.out.println(lucky); // you'll get a number close to 100000
        }
    }
    

    If you want something like 34% you could use rand.nextInt(100) < 34.

提交回复
热议问题