2016-07-27 22 views
-4

可以说,我有3个整数:为两个常量值之间的整数赋值?

int a, b, c; 
b = 25; 
c = 10; 

现在我想a是25或10,但通过随机不一样的东西:

a = b; 

我想是这样的if语句:

a = b || c; 

我该如何实现它?

+3

你应该在询问之前使用Google搜索,也许? – jayeshsolanki93

+0

@ jayeshsolanki93也许我GOOGLE了它,我没有找到答案? :) – Chunrand

回答

7
if(Math.random() < 0.5) 
    a = 25; 
else 
    a = 10; 

Math.random()返回从0到1的随机数,因此,如果你想要的东西是真实的可能性为50%,只是检查它是否是(或大于)0.5小于。

4

一个办法是采取时间米利斯喜欢做的事:

if(System.currentTimeMillis() % 2 == 0){ 
    a=b; 
} else{ 
    a=c; 
} 
+2

除非'System.currentTimeMillis'的分辨率是偶数,在这种情况下它总是使用b。 – immibis

+0

如果您查询速度足够快(比分辨率快),它也会多次返回相同的数字。 – Hulk

+0

那么你必须使用nano秒,如果你使用它快速,顺便说一句,Math.random()使用相同的逻辑来产生随机数,只需将它与数字分开,使其在0到1之间 –

2

试试下面的代码:

Random rand = new Random(); 
int myRandom = rand.nextInt(2); // will be 0 or 1 
if (myRandom == 0) { 
    a=b; 
} else { 
    a=c; 
} 
3

@immibis的回答是实现这一目标的最简单方法。

可测性,我会强烈建议您使用显式Random实例,而不是使用Math.random()

static int pickRandomValue(Random r, int b, int c) { 
    return r.nextInt(2) == 1 ? b : c; 
} 

这可以让你注入模拟Random实例,让你解决,当你需要的行为测试具体的行为。非确定性测试是一种痛苦,应该避免。