java - 正面或反面有 3 个硬币,直到所有 3 个硬币都落在正面

标签 java

我似乎无法让它发挥作用,因为我陷入了困境。 我不知道 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);

最佳答案

如果您假设在抛出 headsnextInt() 返回 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 的内容,而不是抛硬币的值。如果您想打印 01,则需要打印 c1。 (与2和3相同)

关于java - 正面或反面有 3 个硬币,直到所有 3 个硬币都落在正面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54946910/

相关文章:

java - Spring:如何下载文件?

java - netty 4 如何从服务器发送消息

java - ANT 脚本中的条件任务执行

java - 使用模式在 Java 中重构重复代码

JavaFX-JFXpanel 错误?

java - 将多个域转换为 Tomcat 应用程序中的路径

java - 如何确定是否从 JAR 文件调用特定类中的方法

java - 非法结果集

java - 如何强制 Hibernate 3.3 或 3.5 使用 CGLib 而不是 Javassist?

Java MVC : How to set changed the main model class properly when another class changed