Dice continuous sum game Java - java

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');
}
}

Related

Roll Dice Simulation Infinite Loop

I'm having a problem with an infinite loop and not 100% sure where the issue is.
I'm unsure if there is an issue within my "while" statement or there's a wrong sign or bracket.
This is my first time doing this and seems it doesn't like my post being "mostly code", so disregard this paragraph of me typing away to remove the message :)
import java.util.Random; // Needed for the Random class
import java.util.Scanner; // Needed for the Scanner class
/**
This class simulates rolling a pair of dice 10,000 times
and counts the number of times doubles of are rolled for
each different pair of doubles.
*/
public class RollDice {
public static void main(String[] args){
final int NUMBER = 10000; // Number of dice rolls
// A random number generator used in
// simulating the rolling of dice
Random generator = new Random();
int die1Value; // Value of the first die
int die2Value; // Value of the second die
int count = -1; // Total number of dice rolls
int snakeEyes = 0; // Number of snake eyes rolls
int twos = 0; // Number of double two rolls
int threes = 0; // Number of double three rolls
int fours = 0; // Number of double four rolls
int fives = 0; // Number of double five rolls
int sixes = 0; // Number of double six rolls
int runAgain = 0; // Sentinel variable
Scanner keyboard = new Scanner(System.in); //Scanner Object
while(runAgain == 0){ //This is a sentinel loop
// TASK #1 Enter your code for the algorithm here
while(count < NUMBER)
{
// Roll both dice
die1Value = generator.nextInt(6) + 1;
die2Value = generator.nextInt(6) + 1;
// Check to see if both dice are equal
if(die1Value == die2Value)
{
// Check dice values and update counts
if(die1Value == 1)
snakeEyes++;
else if(die1Value == 2)
twos++;
else if(die1Value == 3)
threes++;
else if(die1Value == 4)
fours++;
else if(die1Value == 5)
fives++;
else
sixes++;
}
count++;
}
// Display the results
System.out.println ("You rolled snake eyes " +
snakeEyes + " out of " +
count + " rolls.");
System.out.println ("You rolled double twos " +
twos + " out of " + count +
" rolls.");
System.out.println ("You rolled double threes " +
threes + " out of " + count +
" rolls.");
System.out.println ("You rolled double fours " +
fours + " out of " + count +
" rolls.");
System.out.println ("You rolled double fives " +
fives + " out of " + count +
" rolls.");
System.out.println ("You rolled double sixes " +
sixes + " out of " + count +
" rolls.");
}
// Reset all counts [Every time you want to run again]
snakeEyes = 0;
twos = 0;
threes = 0;
fours = 0;
fives = 0;
sixes = 0;
count = 0;
// Ask the user if they wish to run again, 0 = yes, -1 = no
System.out.println("Do you wish to run again?");
System.out.println("Enter a 0 for yes or a -1 for no");
// Read user's response
runAgain = keyboard.nextInt();
}
}
I formatted your code and in addition to what Brakke Baviaan Says, this part of your code should be inside the while loop:
// Reset all counts [Every time you want to run again]
snakeEyes = 0;
twos = 0;
threes = 0;
fours = 0;
fives = 0;
sixes = 0;
count = 0;
// Ask the user if they wish to run again, 0 = yes, -1 = no
System.out.println("Do you wish to run again?");
System.out.println("Enter a 0 for yes or a -1 for no");
// Read user's response
runAgain = keyboard.nextInt();
Currently is outside so thats why it keeps looping as you never get to update the variable runAgain
You are using a sentinel variable. A sentinel variable is a variable that controls the termination of a loop. In your case, as the comment points out, the sentinel variable runAgain never gets updated, thus the loop will continue infinately.
Boolean sentinel = true;
while(sentinel){
doSomething();
if(someCondition == true){
sentinel = false; //loop will end after function reaching this point
};
The count reset should be inside the first while.

having a problem with java for game simulation

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 + "%");
}
}

Creating a Java Game Pig

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$

Dice roll combinations java

I'm having some troubles getting this code to look neat since there are som many IF & OR statement that needs to be evaulated.
Idea: You throw five dices and pick out e.g. three of the same type 1,1,1 and throw dice the other two again and go gather points.
The tricky thing is to compare dice1,dice2,dice3,dice4,dice5 with the set of rules in order to determine how many points the player get. What code would check all the possible combination "if dicex=1 & dicex=1 & dicex=1" give player 1000 points?
int player1points = 0;
int player2points = 0;
Scanner in = new Scanner(System.in);
Random n1 = new Random();
int dice1 = n1.nextInt(6) + 1;
int dice2 = n1.nextInt(6) + 1;
System.out.println("Dice 1 shows " +dice1);
System.out.println("Dice 2 shows " +dice2);
System.out.println("Dice 3 shows " +dice3);
System.out.println("Dice 4 shows " +dice4);
System.out.println("Dice 5 shows " +dice5);
if /* 1+1+1+1+1 = 2000 */ (dice1==1&&dice2==1&&dice3==1&&dice4==1&&dice5==1){
System.out.println("You got 2000 points! Throw again?");
int points2000 = 2000;
player1points = player1points + points2000;
System.out.print("You have ");
System.out.print(player1points);
System.out.print(" points. Do you want to throw again?");
System.out.println("Yes/No?");
s = in.nextLine();
}
else if /* 1+1+1 = 1000 */ (dice1==1&&dice2==1&&dice3==1||dice2==1&&dice3==1&&dice4==1||dice3==1&&dice4==1&&dice5==1|| dice4==1&&dice5==1&&dice1==1||dice5==1&&dice1==1&&dice2==1||dice1==1&&dice2==1&&dice4==1||d ice2==1&&dice3==1&&dice5==1||dice3==1&&dice4==1&&dice1==1||dice4==1&&dice5==1&&dice1==1||dice1==1&&dice3==1&&dice5==1){
System.out.println("You got 1000 points!");
int points1000 = 1000;
player1points = player1points + points1000;
System.out.print("You have ");
System.out.print(player1points);
System.out.print(" points. Do you want to throw again?");
System.out.println("Yes/No?");
s = in.nextLine();
}
Put the results of the rolls into an arrayList, then just count the number of times the same number shows up in that array list? If there are 3 1's, give 1000 points, else if there are 5 1's give 2000 points.
So for your code you'll have the same beginning for the most part. Add in methods to populate the array list, and to iterate though/count the results of the dice rolls and return the most common and the number of times it shows up.
int player1points = 0;
int player2points = 0;
int count = 0;
int mostCommon = 0;
int maxCount = 0;
ArrayList<Integer> diceRolls = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
Random n1 = new Random();
//rollDice method (parameter would be number of dice to roll)
//checkResults method (count number of times each number 1-6 shows up)
if(maxCount == 3){
player1points += 1000;
//re-roll 2 dice if necessary
else if(maxCount == 5){
player2points += 2000;
//re-roll dice if wanted
That's just one way you could do it. Also it's always good practice to break big blocks of code down into more reader-friendly functions, and it makes debugging easier! If you need anymore help feel free to ask!

Java Setting variable zero to beging another game, but not working

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';
}

Categories

Resources