问题描述
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); }}代码如上。会在有?:这一行报错,把这一行改成(rand.nextInt(2) == 0) ? timesOfZero++ : timesOfOne++;也会报错但是改成如下就不会错了 (j = rand.nextInt(2) == 0) ? timesOfZero++ : timesOfOne++;我想知道为什么
解决方案
表达式的结果要有参数去接受,例如int k = (j == 0) ? timesOfZero++ : timesOfOne++;这样的式子是可以运行的
解决方案二:
三元操作:result = (表达式)? a:b;你没有result,三元操作,结果呢?ps:eclipse 有详细的提示。细心看一下。