Java, questions about switches and cases?

前端 未结 5 421
轻奢々
轻奢々 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:09
    Random rand = new Random(50);
    
    int n = rand.nextInt(11);
    
    if(n<=6)
       do action 1
    else
       do action 2
    

    You need to use nextInt(n) to generate a number between 0 (inclusive) and n (exclusive). In this case we use 11 which gives us a number between 0 and 10. Anything below 6 (60% chance) we do action 1 otherwise do action 2.

    See this for more details on the Random class.

    Using a switch statement is only useful if you have a lot of actions you want to perform, where the action performed depends on something. For example a different action is performed based on the current month. Its quicker than writing if-else statements.

    0 讨论(0)
  • 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;  
    }
    
    0 讨论(0)
  • 2021-01-26 16:13

    If you want same action to happen for multiple cases, then don't put break. For example

    case 1:
    case 2:
    do action 1; break;
    

    In this case, action 1 will happen for both case 1 and 2.

    0 讨论(0)
  • 2021-01-26 16:26

    All you can do is do not apply break in between like

    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
    do action 1;
    break
    case 6:
    case 7:
    do action 2;
    break
    default : break;
    

    or use if-else if you have range of value ..

    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
提交回复
热议问题