java
beginner level
NO ARRAYS in program
Flip a coin (Assignment)
How many times in a row can you flip a coin and gets heads?
Use the random number generator to simulate the flipping of the coin. 0 means heads, 1 means tails.
Start a loop,
flip it, if heads, count it and keep flipping.
If tails, stop the loop.
Display the number of times in a row that heads came up.
Once this is working, wrap a while loop around the loop that flips the coin to play again if the user says they want to.
Run and test this loop.
Sample Output: You flipped the coin and got HEADS 0 times in a row!
Want to try again? (Y or N) Y
You flipped the coin and got HEADS 3 times in a row!
Want to try again? (Y or N) N
Thank you for playing. Have a good day.
Code
import java.util.Scanner;
public class Flip {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
while(true) //loop till enters N
{
int c=0;
while(true) //loop till tail flipped
{
int r=(int)(Math.random() * 2);
if(r==0)
{
c++;
}
else
{
break;
}
}
System.out.println("You flipped the coin and got HEADS "+c+" times in a row!");
System.out.print("Want to try again? (Y or N) ");
char ch=in.next().charAt(0);
if(ch=='N')
{
System.out.println("Thank you for playing. Have a good day.");
break;
}
}
}
}
Terminal Work
.
Get Answers For Free
Most questions answered within 1 hours.