我需要几行Java代码,它们随机运行命令x%的时间.
伪代码:
boolean x = true 10% of cases.
if(x){
System.out.println("you got lucky");
}
Run Code Online (Sandbox Code Playgroud)
Whi*_*g34 27
你只需要这样的东西:
Random rand = new Random();
if (rand.nextInt(10) == 0) {
System.out.println("you got lucky");
}
Run Code Online (Sandbox Code Playgroud)
以下是衡量它的完整示例:
import java.util.Random;
public class Rand10 {
public static void main(String[] args) {
Random rand = new Random();
int lucky = 0;
for (int i = 0; i < 1000000; i++) {
if (rand.nextInt(10) == 0) {
lucky++;
}
}
System.out.println(lucky); // you'll get a number close to 100000
}
}
Run Code Online (Sandbox Code Playgroud)
如果你想要34%的东西,你可以使用rand.nextInt(100) < 34.
Jac*_*ack 20
如果到时候你的意思是代码执行的时间,那么你想要一些代码块内的东西,执行整个块的次数是10%,你可以这样做:
Random r = new Random();
...
void yourFunction()
{
float chance = r.nextFloat();
if (chance <= 0.10f)
doSomethingLucky();
}
Run Code Online (Sandbox Code Playgroud)
当然0.10f代表10%,但你可以调整它.像每个PRNG算法一样,这通过平均使用来工作.除非yourFunction()被称为合理的次数,否则你不会接近10%.