I have written some codes for a game. The game will toss three coins at the same time: a quarter, a dime and a nickel. If a head appears on any of the coins, you win the facevalue of the coin. For example, if the toss resulted in heads for the quarter, heads for the dime and tails for the nickel, you will get: 25 cents plus 10 cents, for a total of 30 cents for the first round. The game will keep on tossing until the total wins get to $1 or the last toss resulted in total wins more than $1.
I have a question to ask the player if he wants to play the game again. But this part does not seem to be working and I can't figure out why.
I have suspect, the part of the code causing the problem is the variable to keep the running score totalRoundWins. I set it to zero for the beginning of the new game, but it does not seem to be working.
This is the code:
import java.util.Scanner; // Needed for the Scanner Class
import java.util.Random; // for the random class
/*
This is a tossing coins for a dollar game
*/
public class oldCoinDemo {
public static void main(String[] args) {
String play; // To ask the player if he wants to play the game.
// Calling the method to decsribe the game
gameDescription();
// Asking the player if he wants to play the game.
Scanner keyboard = new Scanner(System.in);
System.out.println("\nWould you like to play the game? Choose y for Yes and n for No: ");
play = keyboard.nextLine();
// calling the method to start the game
startingGame(play);
}
public static void gameDescription() {
System.out
.println("This is a tossing coins for a dollar game. The game will toss three coins at the same time: a quarter, a dime and a nickel.");
System.out
.println("\nIf a head appears on any of the coins, you win the facevalue of the coin. For example, if the toss resulted in heads for ");
System.out
.println("the quarter, heads for the dime and tails for the nickel, you will get: 25 cents plus 10 cents, for a total of 30 cents for the first round");
System.out.println("\nThe game will keep on tossing until the total wins get to $1 or the last toss resulted in total wins more than $1");
System.out.println("If the total wins is exactly $1, you win $1 otherwise you win nothing.");
System.out.println("\nIt will cost you to 1 cent to play the game");
}
public static void startingGame(String play) {
String again = "y"; // To ask the player whether he wants to play the game again after the first round
String quarterSide; // to get the quarter side for the wins
String dimeSide; // to get the sime side for the wins
String nickelSide; // to get the nickelSide for the wins
double wager = 1; // to calculate the wager for each game
double totalWager = 0; // to get the total wager if the player decides to play the game multiple times
double winsQuarter = 0; // To get the quarter wins after each round of toss
double winsDime = 0; // To get the dime wins after each round of toss
double winsNickel = 0; // To get the nickel wins after each round of toss
double totalRoundWins = 0; // Accumulator for total wins each round of toss
double totalGameWins = 0; // Accumulator for total wins if player plays multiple games
char stop = ' '; // to stop the game if the first time total wins is equal to 1 or greater than 1
// Creating three instances of the coin class
Coin quarter = new Coin();
Coin dime = new Coin();
Coin nickel = new Coin();
if (play.equalsIgnoreCase("y")) {
while (again.equalsIgnoreCase("y")) {
do {
// Toss the coins
quarter.toss();
dime.toss();
nickel.toss();
if (quarter.getSideUp().charAt(0) == 'h')
winsQuarter = 25;
else
winsQuarter = 0;
if (dime.getSideUp().charAt(0) == 'h')
winsDime = 10;
else
winsDime = 0;
if (nickel.getSideUp().charAt(0) == 'h')
winsNickel = 5;
else
winsNickel = 0;
totalRoundWins += (winsQuarter + winsDime + winsNickel);
if (totalRoundWins == 100 || totalRoundWins > 100) stop = 's';
} while (stop != 's');
if (totalRoundWins == 100) {
totalGameWins++;
System.out.println("\nCongratulations! You have just won $1.00");
} else {
System.out.println("\nSorry you did not win");
System.out.println("The total winnings from this round is: $" + totalRoundWins);
}
// Getting the total wager for playing multiple times
totalWager += wager;
// to clear total round wins for another game.
totalRoundWins = 0;
// Asking the player if he wants to play the game.
Scanner keyboard = new Scanner(System.in);
System.out.println("\nWould you like to play the game again? Each Game would Cost you 1 cent. Choose y for Yes and n for No: ");
again = keyboard.nextLine();
}
System.out.printf("Your total wins from the game is: $" + "%.2f", totalGameWins);
System.out.printf("\nYour total wager for the game is: $" + "%.2f", totalWager / 100.0);
System.out.println("\nThank you for playing the game. Goodbye!");
} else if (play.equalsIgnoreCase("n")) {
System.out.println("Goodbye!");
}
}
}
Thank you for the help.
do {
// Toss the coins
quarter.toss();
dime.toss();
nickel.toss();
if (quarter.getSideUp().charAt(0) == 'h')
winsQuarter = 25;
else
winsQuarter = 0;
if (dime.getSideUp().charAt(0) == 'h')
winsDime = 10;
else
winsDime = 0;
if (nickel.getSideUp().charAt(0) == 'h')
winsNickel = 5;
else
winsNickel = 0;
totalRoundWins += (winsQuarter + winsDime + winsNickel);
if (totalRoundWins == 100 || totalRoundWins > 100) stop = 's';
} while (stop != 's');
Take a look at that. You initialize the winDime and what not when its heads. Lets say they all land heads, thats 25 + 10 + 5, total of 40. 3 games of all heads, and thats a total of 120. Instead of saying totalRoundWins++, you are adding the total value of the win to it.
To solve this:
int roundWins = 0;
int totalAmount = 0;
int quarterAmount = 0;
int dimeAmount = 0;
int nickleAmount = 0;
char stop = ' ';
while(stop != 's') {
do {
tossCoins();
if(quarter == heads)
quarterAmount += 25;
if(dime == heads)
dimeAmount += 10;
if(nickle == heads)
nickleAmount += 5;
totalAmount += quarterAmount + dimeAmount + nickleAmount;
}while(totalAmount < 100);
quarterAmount = 0;
dimeAmount = 0;
nickleAmount = 0;
roundWins++;
if(roundWins == 100) stop = 's';
}
Related
I'm new to programming and trying to make a dice game. The game consists of three dice and involves the sum of 12 (on any number of dice) in each round. Each dice can only be rolled once per round.
In each round, the player must be able to choose between: 1 to roll the dice 1, 2 to roll the dice 2, 3 to roll the dice 3, q to exit the game. The program must randomly find a value on the selected dice and then calculate the score. The program should also present the number of wins and the number of rounds lost. The program should continue until the user chooses to cancel the game. Regardless of the number of dice, and the definition of loss is a sum exceeding 12 after all three dice have been rolled. If the sum after three rolls is less than 12, there will be no profit or loss, but you go straight to the next round.
So currently my code works for 1 round, the problem begins when the second round begins. The new dice rolls are just the input I give it, and not a random value (1-6).
How can I make this work?
import java.util.Scanner;
import java.util.Random;
public class Main{
//Declaring int variables for all 3 dice
static int dice1;
static int dice2;
static int dice3;
//Declaring true/false for which dice that is thrown, can't be thrown more than 1 time in each round.
static boolean dice1Thrown = false;
static boolean dice2Thrown = false;
static boolean dice3Thrown = false;
//Method for which dice is thrown - the input the user choses (1, 2, 3 or q)
static char diceToThrow;
//Method that checks what number 1-6 the dice roll. sum by default is 0
static int sum = 0;
//Method for keep track of # wins
static int wins;
//Method keep tracks of # losses
static int losses;
//If firstGame = true it will print "Welcome to the game 12" if false, it doesn't print that every round
static boolean firstGame = true;
//Int for keeping track of when dice thrown is = 3. Go to next round.
static int rounds;
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
if(firstGame)
{
System.out.println("Welcome to the game 12. You must roll 1-3 dice and try to get the sum 12 ... ");
firstGame = false;
}
System.out.printf("Enter which dice you want to roll [1,2,3] (exit with q): ");
//Calling method diceToThrow, chosing input 1,2,3 or q
diceToThrow = scan.next().charAt(0);
tärningsKast(diceToThrow);
//sum = dice1 + dice2 + dice3
calcSum();
//If user gets 12 store int wins as +1, if lose store int loss as +1
winOrLose();
//Printing dices, if input from user is 1, it shows sum of first dice etc.
System.out.printf(dice1 + " " + dice2 + " " + dice3 + " sum: " + sum + " #win: " + wins + " #loss: " + losses+ " ");
//Calling method for round score.
checkRounds();
main(args);
//Method created for sum calculating, called in Main method
}static void calcSum(){
sum = (dice1 + dice2 + dice3);
}
//Method created for dice1, dice2, dice3 and char q (as exit). Dice generates random number between 0-5 and always adds + 1 (1-6)
static void tärningsKast(char diceToThrow){
Random rand = new Random();
//If user input = 1, generate dice1
if(diceToThrow == '1' && !dice1Thrown){
dice1 = rand.nextInt(6) + 1;
dice1Thrown = true;
}
//If user input = 2, generate dice2
else if(diceToThrow == '2' && !dice2Thrown){
dice2 = rand.nextInt(6) +1;
//If user input = 3, generate dice3
}else if(diceToThrow == '3' && !dice3Thrown){
dice3 = rand.nextInt(6) + 1;
dice3Thrown = true;
//If user input = char q, Print "Game Over!" and exit game.
}else if(diceToThrow == 'q'){
System.out.println("Game Over!");
System.exit(0);
}
}
static void winOrLose(){
if(sum == 12){
wins++;
}
else if(sum > 12){
losses++;
}
}
static void checkRounds(){
rounds++;
if(rounds == 3)
{
System.out.println("\n" + "Next round!");
dice1 = 0;
dice2 = 0;
dice3 = 0;
rounds = 0;
}
}
}
When you are going for the next round, the method tärningsKast() is only going to work again and again once each round passes if the dice is not thrown.
Meaning that once a round finishes and you are going to start another round, you have to set that the dices are not thrown, since the round is going to start right after.
The solution I found is to set the dice1Thrown, dice2Thrown and dice3Thrown to false on the if statement that prints that the next round is starting.
static void checkRounds(){
rounds++;
if(rounds == 3)
{
System.out.println("\n" + "Next round!");
dice1 = 0;
dice2 = 0;
dice3 = 0;
rounds = 0;
dice1Thrown = false;
dice2Thrown = false;
dice3Thrown = false;
}
After that the game seems to be working fine.
The steps I made to find that it, were:
Set a break point to debug the line that prints "Next round".
Once the debugger reachs that line, set a break point in the first line of the method tärningsKast(), then check that in each check of the if, else if and etc. the diceNThrown variables are all still setted to true, so none of the conditions will match.
Regarding the question:
"You mean, if you wanted to stop the game in the round 2 ?"
"Yeah exactly like that"
First I'd use you checkRounds() method to check if it were to stop the game, meaning if the user already played two rounds.
Second I would move the logic that move to the next round to a method that checks attemps, intead of rounds, since we will move to the next round every time the user already had three attempts.
And finally before moving to the next round I would be increasing the number of rounds, and right after checking if the number of rounds if the expected number of rounds to stop, that way you can play the game with the limit of rounds you desire to.
//Declaring int variables for all 3 dice
static int dice1;
static int dice2;
static int dice3;
//Declaring true/false for which dice that is thrown, can't be thrown more than 1 time in each round.
static boolean dice1Thrown = false;
static boolean dice2Thrown = false;
static boolean dice3Thrown = false;
//Method for which dice is thrown - the input the user choses (1, 2, 3 or q)
static char diceToThrow;
//Method that checks what number 1-6 the dice roll. sum by default is 0
static int sum = 0;
//Method for keep track of # wins
static int wins;
//Method keep tracks of # losses
static int losses;
//If firstGame = true it will print "Welcome to the game 12" if false, it doesn't print that every round
static boolean firstGame = true;
//Int for keeping track of when dice thrown is = 3. Go to next round.
static int attempts;
// keeping track of the number of rounds
static int rounds = 0;
// desired number of rounds to play
static final int LIMIT_OF_ROUNDS = 5;
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
if(firstGame)
{
System.out.println("Welcome to the game 12. You must roll 1-3 dice and try to get the sum 12 ... ");
firstGame = false;
}
System.out.printf("Enter which dice you want to roll [1,2,3] (exit with q): ");
//Calling method diceToThrow, chosing input 1,2,3 or q
diceToThrow = scan.next().charAt(0);
tärningsKast(diceToThrow);
//sum = dice1 + dice2 + dice3
calcSum();
//If user gets 12 store int wins as +1, if lose store int loss as +1
winOrLose();
//Printing dices, if input from user is 1, it shows sum of first dice etc.
System.out.printf(dice1 + " " + dice2 + " " + dice3 + " sum: " + sum + " #win: " + wins + " #loss: " + losses+ " ");
//Calling method for round score.
checkAttempts();
main(args);
//Method created for sum calculating, called in Main method
}static void calcSum(){
sum = (dice1 + dice2 + dice3);
}
//Method created for dice1, dice2, dice3 and char q (as exit). Dice generates random number between 0-5 and always adds + 1 (1-6)
static void tärningsKast(char diceToThrow){
Random rand = new Random();
//If user input = 1, generate dice1
if(diceToThrow == '1' && !dice1Thrown){
dice1 = rand.nextInt(6) + 1;
dice1Thrown = true;
}
//If user input = 2, generate dice2
else if(diceToThrow == '2' && !dice2Thrown){
dice2 = rand.nextInt(6) +1;
//If user input = 3, generate dice3
}else if(diceToThrow == '3' && !dice3Thrown){
dice3 = rand.nextInt(6) + 1;
dice3Thrown = true;
//If user input = char q, Print "Game Over!" and exit game.
}else if(diceToThrow == 'q'){
System.out.println("Game Over!");
System.exit(0);
}
}
static void winOrLose(){
if(sum == 12){
wins++;
}
else if(sum > 12){
losses++;
}
}
static void checkAttempts(){
attempts++;
if(attempts == 3)
{
rounds++;
checkRounds(rounds);
System.out.println("\n" + "Next round!");
dice1 = 0;
dice2 = 0;
dice3 = 0;
attempts = 0;
dice1Thrown = false;
dice2Thrown = false;
dice3Thrown = false;
}
}
static void checkRounds(int rounds) {
if (rounds == LIMIT_OF_ROUNDS) {
tärningsKast('q');
}
}
User inputs integer value for gamblers starting bankroll
User inputs integer value for gamblers desired bankroll – if the gambler’s bankroll reaches this value he quits the game
User inputs integer value for the number of trials to perform – each trial will consist of enough games to either reduce the gamblers bankroll to zero or increase it to the desired bankroll
Declare an integer variable (set to zero) to keep track of the number of wins
The solution, obviously, will consist of nested looping structures and selection structures
First (outer loop) will loop to perform the required number of trials
Set cash equal to stake
Second (inner loop) will simulate the results of one card game. This loop will repeat as long as cash is greater than zero and less than the desired bankroll
Assume that the gambler has chance of winning the game of less than 50%
Use a random number generator to determine if the gambler won the game
If the gambler won, add $1.00 to his cash
Otherwise subtract $1.00 from his cash
At the end of the inner loop (one game is run) -
If the value of cash equals the gamblers desired bankroll, then increment wins by one
After the outer loop stops, print to the screen the number of wins out of the number of trials and the percent of games won.
trying to get a game simulator to count the number of games won after the total starting amount reaches the end amount. part of it works but not all of it
then it should do that x number of times. https://github.com/samuelatlas/gamesimulation/tree/master
'''
// demonstrating the Java for loop
import java.util.Scanner; // import a scanner c
import java.security.SecureRandom; // imports a secure random class
class newLoopTest1
{
public static void main(String[] args)
{
// OUTER -------LOOP
Scanner input = new Scanner(System.in);
System.out.print("Enter the start bankroll ");
int startBankRoll = input.nextInt();
//int desiredBankRoll = 5;
System.out.print("Enter the desired bankroll ");
int desiredBankRoll = input.nextInt();
System.out.print("Enter the number of trials ");
int numberTrials = input.nextInt();
//int startBankRoll = 2;
int i = 1;
int current = startBankRoll;
int wins = 0;
//int numberTrials = 0;
//OUTER----LOOP
while(i <= numberTrials)
//while(numberTrials <= 4)
{
i++;
int innerloop = 0;
System.out.println("printing from outer");
//INNER----LOOP
while((startBankRoll < desiredBankRoll) && (startBankRoll > 0))
{
SecureRandom randomNumber = new SecureRandom();
int number = randomNumber.nextInt(101);
System.out.println("Before hand start amount of " +
startBankRoll + " end amount of " + desiredBankRoll);
System.out.println("Rolled " + number);
if( number <= 50)
{
System.out.println("lost");
startBankRoll--;
System.out.println("After hand start amount of " +
startBankRoll + " end amount of " + desiredBankRoll);
}
else
{
System.out.println("won");
startBankRoll++;
System.out.println("After hand start amount of " +
startBankRoll + " end amount of " + desiredBankRoll);
}
System.out.println(" Outerloop ran " + numberTrials + "
Innerloop ran " + innerloop);
innerloop++;
//INNER----LOOP
}
//OUTER----LOOP
numberTrials += 1;
//wins++;
System.out.println("Current" + current);
if(startBankRoll == desiredBankRoll)
{
wins += 1;
startBankRoll = current;
System.out.println("wins" + wins);
}
else
{
startBankRoll = current;
System.out.println(" lost all cash");
}
//OUTER----LOOP
}
int totalWins = (wins/(numberTrials-1));
System.out.println("Won " + wins + " out of " + (numberTrials-1));
//System.out.println("total percent" + wins/totalWins );
}
}
The main problem with your code seems to lie with understanding the problem. I took at look at the Github page you linked (I noticed your assignment is due tomorrow -- please do not wait until the last minute to ask for help in the future, and always ask the teacher first, rather than some stranger on Stack Overflow). Let's break down the assignment properly.
The player starts with cash (in your case, 2 units), so we know how to initialize startCash, which you've done properly
His goal is to get to 10 units or bust, so we know the upper and lower limits that define the parameters for his participation in the game. In other words, he only plays while he has > 0 and < 10 units. An outer loop checking to see if he has enough cash is pointless.
While those conditions are true, he plays a coin flipping game, where 50 or less is a loss of one unit and 51 or more is a win of one unit. Each time he flips, we increment a counter so we know how many coin flips he conducted to get to either 0 or 10.
Notice how I've rephrased the question: While cash > 0 and cash < 10, flip coin. If flip < 50, player loss, else win. Increment counter. That's all there is to it, all in one loop.
You confused yourself by adding an outer loop which you don't need at all -- maybe you put it there to keep flipping while the player has money, but it's redundant because your do...while is checking both the lower and upper limits for whether the game should be played. That outer loop is also running 5 times, but what if it takes more than 5 trials to bust or get 10?
I've simplified the code here by basically rearranging what you already had. Compare what you have to what I have and you'll see that I more or less just stripped away the useless outer loop. Run the code a few times and you'll see that you already had more or less the correct logic before you shot yourself in the foot.
import java.security.SecureRandom;
public class Homework
{
public static void main(String[] args)
{
int startCash = 2;
int endCash = 10;
int currentCash = startCash;
int counter = 0;
while(currentCash > 0 && currentCash < endCash)
{
SecureRandom randomNumber = new SecureRandom();
int number = randomNumber.nextInt(101);
if(number <= 50)
{
// lost
currentCash--;
}
else
{
// won
currentCash++;
}
counter++;
}
System.out.println("Current Cash: " + currentCash);
System.out.println("Trials: " + counter);
}
}
The only "major" change other than removing the extra loop is changing your do...while into a while loop. The difference is that a do...while will always run at least once because the exit condition isn't checked until after the code block runs, which doesn't seem correct because what if startCash is already 0 or 10? The while loop checks the condition before running the code block, so if the player is ineligible to play (too much or too little cash), then he doesn't play.
well i figured it all out just took a while and lots of versions. here is the final code. most of the earlier code was to see where the numbers where going.
{import java.util.Scanner; // import a scanner class.
import java.security.SecureRandom; // imports a secure random class.
class TheGambler
public static void main(String[] args)
{
// OUTER -------LOOP AREA
// create scanner for object.
Scanner input = new Scanner(System.in);
//prompt users for the starting bankroll amount.
System.out.print("Enter the start bankroll ");
int startBankRoll = input.nextInt();
//prompt users for the desired bank roll amount.
System.out.print("Enter the desired bankroll ");
int desiredBankRoll = input.nextInt();
//prompt users for the number of tirals.
System.out.print("Enter the number of trials ");
int aNumber = input.nextInt();
//to reset the value after to inner loop has ran.
int current = startBankRoll;
// keep track of number of wins.
int wins = 0;
// keep track of numberTrials.
int numberTrials = 1;
//OUTER----LOOP AREA
//condition for the outer while loop to continue.
while(numberTrials <= aNumber)
{
// number of time inner loops executes.
int innerloop = 0;
//INNER----LOOP
// condition for the inner while loop to continue.
while((startBankRoll < desiredBankRoll) && (startBankRoll > 0))
{
//create a random number and assign it an integer named number.
SecureRandom randomNumber = new SecureRandom();
int number = randomNumber.nextInt(101);
//condition to determine if player wins or a losses.
if( number <= 50)
{
// if losses subtract one from startamount.
startBankRoll--;
}
else
{
// if wins adds one to startamount.
startBankRoll++;
}
// add one to the inner loop count.
innerloop++;
//INNER----LOOP AREA
}
//OUTER----LOOP AREA
//add to the total number of trials ran
numberTrials += 1;
// condition to add one to wins if startamount is equal to desiredamount.
if(startBankRoll == desiredBankRoll)
{
// adds one to the wins count and resets the startamount.
wins += 1;
startBankRoll = current;
}
else
{
//if startamount equals zero reset the startamount.
startBankRoll = current;
}
//OUTER----LOOP AREA
}
// determine total number of games played.
int total = (numberTrials-1);
// converts the amount of wins to a percent.
int percent = wins * 100 / total;
//displays how many wins out of total amount of games played.
System.out.println("Won " + wins + " out of " + total);
//displayes the percent of games won.
System.out.println(percent + "%");
}
}
I just started learning java so I may not even be on the right track but I have an assignment that asks me to create a game of 21. The way the game works is that a player and computer take turns entering either a 1, 2, or 3. The player that enters a number that meets or exceeds 21 loses. The trouble I seem to be having is that I cannot seem to get the program to exit the loop when the final number is entered and it will display that the player loses every time, win or lose.
I have tried using another if statement after the do-while loop to display either "You Win!" or "You Lost." However, I can't figure out what parameters I should use in the if statement to decide who won. I also tried to set the game up with the player as even numbers and the computer as odd numbers but I couldn't get the numbers to add to a running total to end the loop.
int numLoops = 0;
int firstCheck;
int points;
Scanner input = new Scanner(System.in);
do
{
System.out.print("\nEnter a 1, 2, or 3 >> ");
points = input.nextInt();
int random = (int )(Math.random() * 3 + 1);
numLoops = points + numLoops + random;
if(numLoops < 21)
{
System.out.println("The computer entered a " + random);
System.out.println("The new total is " + numLoops);
}
else
{
//This is what always prints.
System.out.println("You lost! The computer is the victor.");
}
}while(numLoops < 21);
//this is what I am having most of my trouble with.
System.out.println("You Win!");
I expect that the loop will close after the total reaches 21 and will output a statement That varies based on who won. However, the program always outputs that the player lost.
If have made a few changes to simplify things. Have a look at the source code, it should be well documented and explains things best.
/*
* Which players turn is it?
* (true for human player, false for computer)
*/
boolean isHumanPlayersTurn = true;
int totalPoints = 0;
Scanner input = new Scanner(System.in);
// the game ending condition
while (totalPoints < 21) {
// take an action, depending on the players turn
if (isHumanPlayersTurn) {
System.out.print("\nEnter a 1, 2, or 3 >> ");
totalPoints += input.nextInt();
} else {
int random = (int) (Math.random() * 3 + 1);
System.out.println("The computer takes " + random);
totalPoints += random;
}
System.out.println("Total amount is " + totalPoints);
/*
* Important part: After each players move, change the players turn, but do NOT
* do this if the game already ended, since then the other player would have won.
*/
if (totalPoints < 21) {
isHumanPlayersTurn = !isHumanPlayersTurn;
}
}
// now, the player to move is the one who loses
if (isHumanPlayersTurn) {
System.out.println("You lost! The computer is the victor.");
} else {
System.out.println("You Win!");
}
After the user enters a number, you should check immediately to see if they hit 21 (and also output the total at that point). If 21 was not hit, then the computer should guess, and then you check again to see if 21 was hit. So you'll have two if statements (one after each guess; user/computer). In the else block after the user guess is where the computer would guess. Your if statement will check for >= 21, indicating a loss for the user or computer as appropriate. You won't need to declare a victor outside of the loop as this can be done inside the loop...
For example:
int total = 0;
do
{
System.out.print("\nEnter a 1, 2, or 3 >> ");
points = input.nextInt();
total = total + points;
System.out.println("The new total is " + total);
if (total >=21)
{
System.out.println("You lost! The computer is the victor.");
}
else
{
int random = (int )(Math.random() * 3 + 1);
total = total + random;
System.out.println("The computer entered a " + random);
System.out.println("The new total is " + total);
if(total >= 21)
{
System.out.println("You Win!");
}
}
}while(total < 21);
I am in the process of creating the java game PIG, each player gets to roll a dice and each turn is added to a score and the first player to get 100 is the winner, the players can choose to roll the dice or hold, if the player rolls and land a 1 their turn is over and all points go to 0, if a player chooses to hold all points gained during the turn are added to her school.
I do however have some issues that i cannot work out, when a user rolls a 1 and their turn would be over and no points given, instead the program gives no output and does not carry on playing (going into an infinite loop??).
edit:
i have since been able to solve the previous issues however i now only get an infinite loop when the program is ran and i do not understand why, Also does anyone know how to make the game replayable after a game has ended?
below is my new code:
//Callum Fawcett
//Game of Pig
//Create: 20/02/2019
//Version 0.1
import java.util.Scanner;
import java.util.Random;
public class game2
{
public static void main(String[] args)
{
int playerScores = 0;
int playerTotal = 0;
int computerScores = 0;
int computerTotal = 0;
int dice;
boolean gameOver = false;
boolean turnOver = false;
char repeat;
String input;
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
System.out.println("Welcome to the game of Pig!\n");
while (gameOver == false)
{
do
{
dice = rand.nextInt(6) + 1;
System.out.println("You rolled: " + dice);
if (dice == 1)
{
playerScores = 0;
System.out.print("You lose your turn! ");
System.out.println("Your total is " + playerTotal);
turnOver = true;
}
else
{
playerScores += dice;
System.out.print("Your turn score is " +
playerScores);
System.out.println(" If you hold you will have " +
playerScores + " points.");
System.out.println("Enter 'r' to roll " +
"again, 'h' to hold.");
input = keyboard.nextLine();
repeat = input.charAt(0);
if (repeat == 'h')
break;
}
} while(turnOver == false || dice != 1);
playerTotal += playerScores;
System.out.println("Your score is " +
playerTotal);
playerScores = 0;
if (playerTotal >= 100)
{
System.out.println("YOU WIN!");
gameOver = true;
}
System.out.println();
System.out.println("It is the computer's turn.");
do
{
dice = rand.nextInt(6) + 1;
System.out.println("The computer rolled: " +
dice);
if(dice == 1)
{
computerScores = 0;
System.out.print("The computer lost its turn!");
System.out.print(" Computer total is " +
computerTotal);
turnOver = false;
}
else
{
computerScores += dice;
if(computerScores >= 20 || (computerTotal +
computerScores) >= 100)
System.out.println("The computer holds");
turnOver = false;
}
} while (dice != 1 || computerScores < 20);
computerTotal += computerScores;
System.out.println("The computer's score is " +
computerTotal + "\n");
computerScores = 0;
if (computerTotal >= 100)
{
System.out.println("THE COMPUTER WINS!");
gameOver = true;
}
if(keyboard!=null)
keyboard.close();
}
}
}
this is an output i get :
TheRealFawcett:lab5 therealfawcett$ java game2
Welcome to the game of Pig!
You rolled: 6
Your turn score is 6 If you hold you will have 6 points.
Enter 'r' to roll again, 'h' to hold.
r
You rolled: 4
Your turn score is 10 If you hold you will have 10 points.
Enter 'r' to roll again, 'h' to hold.
r
You rolled: 1
You lose your turn! Your total is 0
Your score is 0
It is the computer's turn.
The computer rolled: 2
The computer rolled: 2
The computer rolled: 1
The computer lost its turn! Computer total is 0The computer's score is
0
You rolled: 2
Your turn score is 2 If you hold you will have 2 points.
Enter 'r' to roll again, 'h' to hold.
Exception in thread "main" java.lang.IllegalStateException: Scanner
closed
at java.base/java.util.Scanner.ensureOpen(Scanner.java:1150)
at java.base/java.util.Scanner.findWithinHorizon(Scanner.java:1781)
at java.base/java.util.Scanner.nextLine(Scanner.java:1649)
at game2.main(game2.java:50)
TheRealFawcett:lab5 therealfawcett$
I'm creating a guessing game in Java using NetBeans. The guessing game allows the user to guess a number between 1 and 10. Each round they have 5 chances to guess the number. There are three rounds in the game. After the user finishes the game, stats are outputted with the minimum # of guess and maximum # of guesses.
The minimum guesses isn't working and it always outputs 1. Right now, I have the program set up so that it keeps track of how many times the user guesses per round. After each round, it compares this value to the min value and max value. The minGuess is set as 5 since it isn't possible to guess more than 5 times. The maxGuess is set as 1 since they will always guess one time or more than one time.
static void numberGuess(int guess, int randNum) { //creating a method to check if the user has guessed the correct number or if the guess should be higher or lower
if (guess < 0 | guess > 10) {
System.out.println("Please enter a valid number between 1 and 10.");
}
else if (guess == randNum) {
System.out.println("You guessed the number correctly");
}
else if (guess < randNum) {
System.out.println("Guess is too low");
}
else if (guess > randNum) {
System.out.println("Guess is too high");
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
/*Rational: This program allows a user to guess a number between 1 and 10 five times per round. There are three rounds in one game.
The program then outputs the stats for the game.
*/
//declaration
int userGuess; //creates a spot in memory for these variables
int numOfGuess = 0;
int invalidGuess = 0;
int minGuess = 5;
int maxGuess = 1;
int average;
Scanner Input = new Scanner (System.in); //creates an object in the scanner clas
//execution
System.out.println("Welcome to Super Guessing Game! Guess a random number between 1 and 10. There are three rounds with one guess each.");
loopOne: //labels the loop as loopTwo
for (int x = 1; x <= 3; x= x + 1 ) { //runs the loop for three rounds
System.out.println(" ");
System.out.println("Round " + x);
System.out.println("To exit the game at any point, enter a negative 1");
System.out.println(" ");
int randNum;
randNum = 1 + (int)(Math.random() * ((10 - 1) + 1)); //generates the random number
loopTwo: //labels the loop as loopTwo
for (int y = 1; y <= 5; y= y + 1) { //runs the loop five times (five guesses per round)
numOfGuess = numOfGuess + 1; //counts number of guesses user has made
System.out.println("Guess " + y + " out of 5");
System.out.println("Please guess a number between 1 and 10: ");
userGuess = Input.nextInt();
if (userGuess == -1){ //sentinel to let the user quit at any time
System.out.println("Thank you for playing");
break loopOne; //breaks out of the loops if the user wants to stop playing
}
numberGuess(userGuess, randNum); //calls the numberGuess method
if (y < minGuess) //compares to see if the minimum number of guesses is less that the number of guesses the user has made this round
minGuess = y;
if (y > maxGuess) //compares to see if the maximum number of guesses is greater than the number of guesses that the user has made this round
maxGuess = y;
if (userGuess <1 | userGuess > 10) { //keeps track of invalid guesses
invalidGuess = invalidGuess + 1;
}
if (userGuess == randNum) { //exits the round if the user guesses correctly
break;
}
}
}
average = numOfGuess / 3; //calculates the average number of guesses
System.out.println("Thanks for playing!"); //outputs the following
System.out.println("");
System.out.println("Number of Guesses Made: " + numOfGuess);
System.out.println("Average Number of Guesses: " + average);
System.out.println("Number of Invalid Guesses: " + invalidGuess);
System.out.println("Minimum Guesses Used: " + minGuess);
System.out.println("Maximum Guesses Used: " + maxGuess);
}
}
y starts at one, and is never less than one, thus minGuess is always one.
for (int y = 1; y <= 5; y= y + 1) {
...
if (y < minGuess)
minGuess = y;
...
}
Consider only updating minGuess and maxGuess upon a successful guess.
Your if statement is at the wrong place.
Your asking every time. also if the user isnt guessing the right number.
so just put it in ur numberguess method:
else if (guess == randNum) {
System.out.println("You guessed the number correctly");
if (y < minGuess) //compares to see if the minimum number of guesses is less that the number of guesses the user has made this round
minGuess = y;
if (y > maxGuess) //compares to see if the maximum number of guesses is greater than the number of guesses that the user has made this round
maxGuess = y;
}