ericrk00
ericrk00

Reputation: 47

Java - Trying to conduct a coin toss script with summary results of 10 coin toss

I'm trying to write a script that will give me a summary of 10 coin toss. I'm stuck on how can I read the result and output as a summary something like this:

C:\Users\javauser\Desktop> java CoinToss
Heads: 3
Tails: 7

Here is my code:

import java.util.Random;
public class CoinToss{
   public static void main(String[] args)
   {
      Random rand = new Random();

        for (int i = 0; i < 10; i++)
        {
            if (rand.nextInt(2) == 0)
                System.out.println("Tails");
            else
                System.out.println("Heads");
        }
    }
}

Upvotes: 1

Views: 237

Answers (2)

Mr00Anderson
Mr00Anderson

Reputation: 854

Keep track of the results instead of printing right away, then print out the end results. I used String format here to keep the String clean from concatenation.

import java.util.Random;
public class CoinToss{
   public static void main(String[] args)
   {
        Random rand = new Random();

        int heads = 0;
        int tails = 0;

        for (int i = 0; i < 10; i++)
        {
            if (rand.nextInt(2) == 0)
                tails++;
            else
                heads++;
        }
        String results = String.format("CoinToss Heads: %d Tails: %d", heads, tails);
        System.out.printLn(results);
    }
}

Upvotes: 3

User1000547
User1000547

Reputation: 4301

You need to keep track of the result of your simulation.

import java.util.Random;
public class CoinToss{
   public static void main(String[] args)
   {
      Random rand = new Random();
      int numHeads = 0;
      int numTails = 0;

        for (int i = 0; i < 10; i++)
        {
            if (rand.nextInt(2) == 0)
                numTails++;
            else
                numHeads++;
        }
        System.out.println("Heads: " + numHeads);
        System.out.println("Tails: " + numTails);
    }

Upvotes: 1

Related Questions