Java,关于开关和案例的问题?

2022-01-19 00:00:00 switch-statement java

所以我想在 60% 的时间里做某个动作,在 40% 的时间里做另一个动作.有时它也不做.我能想到的最好方法是通过开关和制作一堆案例.如果这对你们没有任何意义,下面是一个示例.我的问题是,有没有更好的方法?有没有办法只在一个语句中执行案例 0-5 并执行操作 1?

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 switches and making a bunch of cases. An example is below if this doesn't make any sense to ya'll. My question is, is there a better way? Is there a way to just do Case 0-5 does action 1 all in one statement?

        Random rand = new Random(50);
        switch(rand.nextInt()) 
        {
        case 1:
        {
            do action 1
        } 
        break;

        case 2:
        {
            do action 1
        }
        break;  
        case 3:
        {
            do action 1
        }
        break;  
        case 4:
        {
            do action 1
        }
        break;  
        case 5:
        {
            do action 1
        }
        break;  
        case 6:
        {
            do action 1
        }
        break;  
        case 7:
        {
            do action 2
        }
        break;  
        case 8:
        {
            do action 2
        }
        break;  
        case 9:
        {
            do action 2
        }
        break;  
        case 10:
        {
            do action 2
        }
        break;  
        }

推荐答案

这样的东西在 IMO 上会更具可读性:

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;  
}

相关文章