[code="java"]public class ThrowCoins {
public static void main(String[] args) {
Random rand = new Random();
int timesOfZero = 0;
int timesOfOne = 0;
int times = 1000000;
int j = 0;
for (int i = 0; i < times; i++) {
j = rand.nextInt(2);
// if (j == 0) {
// timesOfZero++;
// } else {
// timesOfOne++;
// }
(j == 0) ? timesOfZero++ : timesOfOne++;
}
System.out.println("Times of zero:" + timesOfZero);
System.out.println("Times of one:" + timesOfOne);
System.out.println("Times:" + times);
System.out.println("The total proportion of 0 is:" + timesOfZero / (double)times);
}
}[/code]
代码如上。会在有?:这一行报错,把这一行改成
code="java" == 0) ? timesOfZero++ : timesOfOne++;[/code]也会报错
但是改成如下就不会错了
[code="java"] (j = rand.nextInt(2) == 0) ? timesOfZero++ : timesOfOne++;[/code]
我想知道为什么