Java:在x%的情况下做一些事情 [英] Java: do something x percent of the time
本文介绍了Java:在x%的情况下做一些事情的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要几行Java代码,这些代码在x%的时间内随机运行命令。
I need a few lines of Java code that run a command x percent of the time at random.
psuedocode:
psuedocode:
boolean x = true 10% of cases.
if(x){
System.out.println("you got lucky");
}
推荐答案
如果是时间你的意思是代码正在被执行的时间,所以你想要在代码块内部执行10%的时间执行整个块的事情你可以做一些事情喜欢:
If by time you mean times that the code is being executed, so that you want something, inside a code block, that is executed 10% of the times the whole block is executed you can just do something like:
Random r = new Random();
...
void yourFunction()
{
float chance = r.nextFloat();
if (chance <= 0.10f)
doSomethingLucky();
}
当然 0.10f
代表10%,但你可以调整它。像每个PRNG算法一样,这通过平均使用来工作。除非 yourFunction()
被称为合理的次数,否则你不会接近10%。
Of course 0.10f
stands for 10% but you can adjust it. Like every PRNG algorithm this works by average usage. You won't get near to 10% unless yourFunction()
is called a reasonable amount of times.
这篇关于Java:在x%的情况下做一些事情的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文