dimanche 18 novembre 2018

How to count and separate consecutive heads or tails flips in java coin flip program?

I'm trying to add spaces and a counter between consecutive runs in a simple java coin toss program.

I want this output: HHHHTHTTTTTTTHTTTHHHTTTTHTTHHHTTTTHHTHHHHHTTTTTTHT

to look print like this: HHHH4 T1 H1 TTTTTTT7 H1 TTT3 HHH3 TTTT4 H1 TT2 HHH3 TTTT4 HH2 T1 HHHHH5 TTTTTT6 H1 T1

I am not sure how to position the conditions in the loop so that spaces and a counter are printed between the consecutive 'T's and 'H's. Do I need to use a different kind of loop? I have tried rearranging the loop and using break; and continue; but haven't gotten the result to print correctly.

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);
    System.out.print("How many times do you want to flip the coin? ");
    int timesFlipped = scnr.nextInt();
    Random randomNum = new Random();


    for (int i=0; i < timesFlipped; i++) {
        int currentflip = randomNum.nextInt(2);
        int previousFlip = 0;
        int tailsCount = 0;
        int headsCount = 0;

        if (currentflip == 0) {
            System.out.print("H");
            previousFlip = 0;
            headsCount++;
        }
        else if (currentflip == 1) {
            System.out.print("T");
            previousFlip = 1;
            tailsCount++;
        }

        if (previousFlip == 0 && currentflip == 1) {
            System.out.print(headsCount + " ");
            headsCount = 0;
        }
        else if (previousFlip == 1 && currentflip == 0) {
            System.out.print(tailsCount + " ");
            tailsCount = 0;
        }

    }


}




Aucun commentaire:

Enregistrer un commentaire