Question: COIN TOSSING: Write a program that simulates the toss of a coin. Provide a menu of two options: toss and quit. Count the number of
COIN TOSSING: Write a program that simulates the toss of a coin. Provide a menu of two options: toss and quit. Count the number of times each side of the coin appears and display the results after each toss. The program should have a method called flip() that is called, takes no arguments and returns a Coin enum value (HEADS or TAILS).
This is my code it runs but the problem is the part of display the results after each toss it only do it when I exit the program and shows the summary. I want to do both display every single toss head or tails and when I choose show results the summary. The only part need to be added is the display the results after each toss.
My code:
import java.io.*; import java.util.Random; public class tosscoinpgm { public static void main (String args[]) { try { int choice = 1,tails = 0,heads = 0; boolean frntvalue; //user input for different choice BufferedReader b = new BufferedReader(new InputStreamReader(System.in)); //creating object of class so that we can access flip method tosscoinpgm obj = new tosscoinpgm(); do { System.out.println(" Enter your choice"); System.out.println(" 1 Toss Coin "); System.out.println(" 2 Show Results"); choice = Integer.parseInt(b.readLine());//reading choice of user using readline() method if (choice == 1) { frntvalue = obj.flip();//flip method return boolean value true or false
if (frntvalue == true)//if condition check fro true or false
{ heads++; } else if (frntvalue == false) { tails++; } } else if (choice == 2) { System.out.println(" No.Of Heads = "+heads); System.out.println(" No.Of Tails = "+tails); } } while (choice != 2);
} catch (Exception e) { System.out.println("Error"+e.getMessage()); }
} boolean flip ( ) { int front; Random randnum = new Random();
front = 1 + randnum.nextInt( 2 );
if (front == 1) { return true; } else if (front == 2) { return false; } return true; } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
