Write a program Coin Flip that accepts user input using Scan
Solution
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

