# Write a program called HeadsOrTails, that lets the user guess whether the flip of a coinresults in heads or tails. The program randomly generates an integer 0 or 1, whichrepresents head or tail. The program prompts the user to enter a guess and reports whetherthe guess is correct or incorrect.1) Create a Scanner2) Declare a variable called coin to be a random number of 0 and 13) Ask the user to enter a guess of 0 or 1 (0: heads, 1: tails)4) If the guess is equal to the coin, print a Message, "You guessed it!"5) Otherwise, print the result and the message, "Better luck next time"Sample Runs:Enter guess of 0 or 1 (0: heads, 1: tails)Invalid input!Enter guess of 0 or 1 (0: heads, 1: tails)0The coin is 1 (tailis) - Better luck next timeEnter guess of 0 or 1 (0: heads, 1: tails)You guessed it!

Question

For this program you need to use Eclipse

Step 1

The program has the following algorithm:

1. Declare the necessary variables within the “main()” function.
2. Create object for “Scanner()” to get the guess from the user (0: heads, 1: tails).
3. If the guess is equal to the coin then print the statement “You guessed it”.
4. Otherwise, print the statement “Better luck next time”.
Step 2

Java program is as follows:

// Import the required package
import java.util.Scanner;

// Definition of class
{
// Definition of main() method
public static void main (String [] args)
{
// Declare required variables
int coin, guess;
String num;

// Generate the random number 0 or 1
coin = (int) (Math.random() * 2);

// Create an object for scanner
Scanner sc = new Scanner(System.in);

// Get an input from user
System.out.println("Enter a guess 0 or 1(0: heads, 1: tails) ");
guess = sc.nextInt();

// Check guess is equal to 0
if (guess == 0)
{
// Condition is true, assign num to heads
}

// Otherwise
else
{
// Assign num to tails
num = "tails";
}

// Check guess is not equal to 0 and 1
if (guess != 0 && guess != 1)
{
// Condition is true, print invalid input
System.out.println("Invalid input!");
}

// Otherwise, Check the guess is equal to coin
else if (guess == coin)
{
// Print the message
System.out.println("You guessed it!");
}

// Otherwise
else
{
// print the message
System.out.println("The coin is " + guess + " (" + num + ")- Better luck next time");
}
}
}
Step 3

The executed output is as follows:

Sample out...

### Want to see the full answer?

See Solution

#### Want to see this answer and more?

Our solutions are written by experts, many with advanced degrees, and available 24/7

See Solution
Tagged in