Thinking in Java Fourth Edition Bruce Eckel Chapter 2 Exercise 7

Exercise 7: Write a program that simulates coin-flipping.

Solution:

import java.util.*;

public class CoinToss
{
    public static void main(String[] args)
    {
        Random rand = new Random();
        int coin = rand.nextInt();
        if(coin % 2 == 0)
        {
            System.out.println("heads");
        }
        else System.out.println("tails");      
    }
}

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *