Java, questions about switches and cases?

前端 未结 5 462
轻奢々
轻奢々 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:13

    Something like this would be much more readable IMO:

    if( Math.random() >= probabilityOfDoingNothing ){
    
        if( Math.random() < 0.6 ){
            action1;
        }else{
            action2;
        }
    }
    

    Re. your question about cases, the following is equivalent to your code:

    Random rand = new Random(50);
    switch(rand.nextInt()) 
    {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        {
            do action 1
        }
        break;
        case 7:
        case 8:
        case 9:
        case 10:
        {
            do action 2
        }
        break;  
    }
    

提交回复
热议问题