Eclipse Java投掷硬币

时间:2019-03-07 15:37:36

标签: java

我需要帮助才能使输出也显示折腾计数,因为现在它仅显示折弯表示头部。尾巴朝向尾巴,以此类推,直到三个头为止,但应该也显示折腾次数。

import java.util.*;
public class Coinrolling {

    public static void main(String[] args) {
        Random rand = new Random(); 
        boolean noConsecutive = true;
        int flipCount = 0;
        int randomFlip;


        while (noConsecutive) {

            randomFlip = rand.nextInt(2) + 1;

            if (randomFlip == 1) { 
                System.out.println("heads"); 
                flipCount++;
            }else { 
                System.out.println("tail"); 
                flipCount= 0;
            }
            if (flipCount == 3) {
                noConsecutive = false;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以用已经拥有tossCount的相同方式添加flipCount变量。您还可以通过检查while来简化flipCount循环条件:

Random rand = new Random();
int flipCount = 0;
int tossCount = 0;
while (flipCount != 3) {
    int randomFlip = rand.nextInt(2) + 1;
    tossCount++;
    if (randomFlip == 1) {
        System.out.println("heads");
        flipCount++;
    } else {
        System.out.println("tail");
        flipCount = 0;
    }
}
System.out.print("tossed " + tossCount + " times");