Hey guys. Bare with me because I am new to Java and am in a class, yet I would love to be great at it at some point. Any advice regarding style, etc. would be great. In this program, I had to make a game where the user bets dollars and guesses if 2 coins land on heads or tails. Everything works, except that in my loop, I want the player to choose whether or not to play again. The program immediately skips to the next part where the player enters his/her guess. Here is the source code and a screen shot of what happens. If you can help me find the issue (which I covered in bold), that would be very helpful as I have been stuck for a while now.
import java.util.Scanner;
import java.util.Random;
public class FlipACoinGame {
public static void main (String [] args) {
Scanner reader = new Scanner(System.in);
Random generator = new Random();
int coin1, coin2, //two coins
dollars, //initial number of dollars(input)
count, //number of tosses to reach depletion
maxDollars, //maximum amount held by the gambler
countAtMax, //count when the maximum is achieved
coin1Guess, coin2Guess; //Player's guess of heads (1) or tails(2)
//Initialize variables
countAtMax = 0;
count = 0;
maxDollars = 0;
//Request the input
System.out.print("How many dollars do you have? ");
dollars = reader.nextInt();
//Loop until the money is gone.
while (dollars > 0){
count++;
String playAgain; //Player inputs yes or no for another round
//Have player input "YES" or "NO" and prediction of heads (1) or tails (2) for each coin.
System.out.print("Thank you for playing \"Flip A Coin.\" Are you sure you still want to gamble?");
playAgain = reader.nextLine();
if (playAgain == "NO"){
break;
}
System.out.print("\nEnter your guess for coin 1 (enter 1 for heads or 2 for tails)");
coin1Guess = reader.nextInt();
System.out.print("\nEnter your guess for coin 2 (enter 1 for heads or 2 for tails)");
coin2Guess = reader.nextInt();
//Flip coins
coin1 = generator.nextInt (2) + 1; //1(heads) or 2(tails)
coin2 = generator.nextInt (2) + 1; //1 (heads) or 2(tails)
//Calculate winnings and/or losses
if (coin1 == coin1Guess||coin2 ==coin2Guess){
dollars += 1;
System.out.println("ONE MATCH! You win 1 dollar! Your new total is " + dollars + ".");
}
else if (coin1 == coin1Guess && coin2 == coin2Guess){
dollars += 4;
System.out.println("TWO MATCHES! You win 4 dollars! Your new total is " + dollars + ".");
}
else {
dollars -= 1;
System.out.println("Sorry, no match. You lose 1 dollar. Your new total is " + dollars + ".");
}
//If this is the new maximum, remember it
if (dollars > maxDollars){
maxDollars = dollars;
countAtMax = count;
}
}
//Display results
System.out.println
("You are broke after " + count + " rounds.\n" +
"You should have quit after " + countAtMax +
" rolls when you had $" + maxDollars + ".");
}
}
FlipACoinGame.jpg