Java,关于开关和案例的问题?
所以我想在 60% 的时间里做某个动作,在 40% 的时间里做另一个动作。有时让它两者都不做。我能想到的最好方法是通过开关并制作一堆案例。如果这对您来说没有任何意义,请看下面的示例。 我的问题是,有更好的方法吗? 有没有办法只在一个语句中执行 Case 0-5 并执行操作 1?
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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这样的东西会更具可读性
IMO: Re. 。您关于案例的问题,以下相当于您的代码:
Something like this would be much more readable IMO:
Re. your question about cases, the following is equivalent to your code:
您需要使用
nextInt(n)
生成 0(含)和 n(不含)之间的数字。在本例中,我们使用 11,它给我们一个 0 到 10 之间的数字。任何低于 6 的值(60% 的机会)我们都会执行操作 1,否则执行操作 2。请参阅 有关 Random 类的更多详细信息。
仅当您要执行大量操作时,使用 switch 语句才有用,其中行动执行取决于某事。例如,根据当前月份执行不同的操作。它比编写 if-else 语句更快。
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.
如果您希望在多种情况下发生相同的操作,则不要放置中断。例如
,在本例中,情况 1 和情况 2 都会发生操作 1。
If you want same action to happen for multiple cases, then don't put break. For example
In this case, action 1 will happen for both case 1 and 2.
您所能做的就是不要在
或
如果您有值范围,请使用 if-else ..
All you can do is do not apply break in between like
or
use if-else if you have range of value ..
“随机”行为有很多方法。有些比其他更容易实现,但它们牺牲了熵桶。 Random() 是一个昂贵的操作。 Switch 对于复杂的信号传递很有用,但对于二元决策是否是您想要的:
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: