Write a program Coin Flip that accepts user input using Scanner. Your program st
ID: 3927482 • Letter: W
Question
Write a program Coin Flip that accepts user input using Scanner. Your program starts the user out with $10. Ask the user how much they want to bet. When the user is guessing the results of a coin toss (whole dollar bets only/integer values) are to be used please notate to the user. The user must enter a number within 1 and the amount that is currently assigned initially or with after each game play. If the user enters a value out of range please relay a message such as "Please enter a number with your range". Next you will ask the user if they are guess "heads" or "tails". Next simulate the flip of a random coin you should include the math class to randomize. If the user guessed correctly, they will double the amount of their bet and you should print a "You win" message otherwise if they lose their bet you should print "You lose". After each coin loss, please ask the user if they want lo quit or not. If they quit, tell them what their pay out was.Explanation / Answer
CoinFlip.java
import java.util.Random;
import java.util.Scanner;
public class CoinFlip {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random r = new Random();
int amount = 10;
while(true){
System.out.println("How much you want to bet: ");
int bet = scan.nextInt();
if(bet <= amount){
System.out.println("Enter your guess(heads or tails): ");
String guess = scan.next();
int toss = r.nextInt(2);
String tossResult = "";
if(toss == 1){
tossResult = "heads";
}
else{
tossResult = "tails";
}
if(tossResult.equalsIgnoreCase(guess)){
amount+=bet;
System.out.println("You win");
}
else{
amount-=bet;
System.out.println("You lose");
}
System.out.println("Do you want to continue(y or n): ");
char ch = scan.next().charAt(0);
if(ch=='n'||ch=='N'){
System.out.println("The pay out is "+amount);
break;
}
}
else{
System.out.println("Please enter a number with your range");
}
}
}
}
Output:
How much you want to bet:
11
Please enter a number with your range
How much you want to bet:
5
Enter your guess(heads or tails):
tails
You lose
Do you want to continue(y or n):
y
How much you want to bet:
6
Please enter a number with your range
How much you want to bet:
4
Enter your guess(heads or tails):
heads
You win
Do you want to continue(y or n):
n
The pay out is 9
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.