Java, questions about switches and cases?

前端 未结 5 463
轻奢々
轻奢々 2021-01-26 15:41

So I want to do a certain action 60 % of the time and another action 40% of the time. And sometimes have it doing neither. The best way I can think to do this is through switche

5条回答
  •  死守一世寂寞
    2021-01-26 16:27

    There are many approaches to "random" behavior. Some are easier to implement than others but these sacrifice the entropy bucket. Random() is an expensive operation. Switch is useful for complicated signalling, but for a binary decision if is what you want:

    int signal = (int)(System.currentTimeMillis() % 5);
    if(signal==0 || signal == 1){
     doActionTwo();//one third of the time
    }else{
     doActionOne();//two thirds of the time
    }
    

提交回复
热议问题