Java, questions about switches and cases?

前端 未结 5 457
轻奢々
轻奢々 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.

提交回复
热议问题