Java: do something x percent of the time

前端 未结 8 784
再見小時候
再見小時候 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条回答
  • 2020-12-09 17:42

    To take your code as a base, you could simply do it like that:

    if(Math.random() < 0.1){
      System.out.println("you got lucky");
    }
    

    FYI Math.random() uses a static instance of Random

    0 讨论(0)
  • 2020-12-09 17:42

    You could try this:

    
    public class MakeItXPercentOfTimes{
    
        public boolean returnBoolean(int x){
            if((int)(Math.random()*101) <= x){ 
                return true; //Returns true x percent of times.
            }
        }
    
        public static void main(String[]pps){
            boolean x = returnBoolean(10); //Ten percent of times returns true.
            if(x){
                System.out.println("You got lucky");
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题