我似乎无法解决这个问题,因为我很困。 我不知道在if语句中该怎么做。 任何帮助将不胜感激。
Random coin1 = new Random();
Random coin2 = new Random();
Random coin3 = new Random();
int count = 0;
int heads = 0;
System.out.println("Toss\tCoin1\tCoin2\tCoin3");
while (heads < 3) {
int c1 = coin1.nextInt(2);
int c2 = coin2.nextInt(2);
int c3 = coin3.nextInt(2);
count++;
if()
System.out.println(count + "\t" +coin1 +"\t" + coin2 + "\t" +coin3);
答案 0 :(得分:1)
您不需要if
。您的随机值为0
或1
。假设值为1
代表Head,则可以使用
heads = c1+c2+c3;
代替那个if
。
答案 1 :(得分:1)
如果假设扔了 heads ,nextInt()
返回1
,则将这些值的总和分配给heads
。
heads = c1 + c2 + c3;
如果您使用if
而不是nextBoolean()
,则还有一个使用nextInt(2)
的选项,如果扔了 heads ,它将返回true
。同样将变量修改为boolean
而不是int
,代码看起来像
while (heads < 3) {
boolean c1 = coin1.nextBoolean();
boolean c2 = coin2.nextBoolean();
boolean c3 = coin3.nextBoolean();
count++;
heads = 0;
heads += c1 ? 1 : 0; //incrementing heads if c1 is true
heads += c2 ? 1 : 0;
heads += c3 ? 1 : 0;
if(c1 && c2 && c3){ }
System.out.println(count + "\t" + c1 +"\t" + c2 + "\t" +c3);
}
在System.out.println(count + "\t" +coin1 +"\t" + coin2 + "\t" +coin3);
coin1
中也引用了Random
对象,这意味着将打印出类似java.util.Random@74a14482
的东西,而不是抛硬币的值。如果要打印0
或1
,则需要打印c1
。 (与2和3相同)
答案 2 :(得分:0)
您可以使用Random
的一个实例
Random rnd = new Random();
int count = 0,heads = 0;
while (heads < 3) {
int c1 = rnd.nextInt(2);
int c2 = rnd.nextInt(2);
int c3 = rnd.nextInt(2);
count++;
heads = c1+c2+c3;
System.out.println(count + "\t" +c1 +"\t" + c2 + "\t" +c3);
}
如果只想打印最终结果:
Random rnd = new Random();
int count = 0,heads = 0;
int c1 = 0, c2 = 0, c3 = 0;
while (heads < 3) {
c1 = rnd.nextInt(2);
c2 = rnd.nextInt(2);
c3 = rnd.nextInt(2);
count++;
heads = c1+c2+c3;
}
System.out.println(count + "\t" +c1 +"\t" + c2 + "\t" +c3);
答案 3 :(得分:0)
//you can use only one rand obj to use Random()
Random rand = new Random();
//Initializing coins as 0
//Values of coins will change once we get random
int coin1 = 0;
int coin2 = 0;
int coin3 = 0;
//initializing heads and count as 0
int heads = 0;
int count = 0;
while(heads < 3){
//Assume '1' comes out for head and '0' for tail
coin1 = rand.nextInt(2);
coin2 = rand.nextInt(2);
coin3 = rand.nextInt(2);
//if all three coins are '1' which is head;
//sum should be 1+1+1 = 3
//while loop terminates because 3<3 is false
heads = coin1+coin2+coin3;
count++; //count = count +1;
}
//printing the value of count and coins
System.out.println(count + "\t" +coin1 + "\t" + coin2 + "\t" +coin3);