Java,关于开关和案例的问题? [英] Java, questions about switches and cases?

查看:34
本文介绍了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;  
}

这篇关于Java,关于开关和案例的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆