我似乎无法让它发挥作用,因为我陷入了困境。 我不知道 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);
最佳答案
如果您假设在抛出 heads 时 nextInt()
返回 1
,则将这些值的总和分配给 头
。
heads = c1 + c2 + c3;
如果您使用 nextBoolean()
而不是 nextInt(2)
,则还可以选择使用 if
,后者将返回 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相同)
关于java - 正面或反面有 3 个硬币,直到所有 3 个硬币都落在正面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54946910/