rolling 2 dice randomly (java) - java

Two dice will be rolled and 2 random numbers between 1 and 6 will be generated. The sum will
be taken from the 2 numbers and used to decide what is next. If user's sum is 3, 5, 7, 9,11 then they
lose. If the sum is 4, 6, 8, 10 then they win. If sum is 2, 12 then the program automatically rolls the
dice again until the user wins or loses.
Create a game for the above algorithm with following constructs in it:
Game should ask the user to input his/ her name.
Game should be able to generate random numbers between 1 - 6.
Program should be able to show 3 alternate paths
a. Win : when the random number is in 4 , 6, 8, 10
b. Loose: 3,5,7,9,11
c. Play again: 2, 12
Basically I need keep getting a new random number if I get sum of 2 or 12 from 2 dice and that has to go into the loop again and again
public class assessmentrollingdicedemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Enter User Name: ");
String userName = sc.next();
Random r = new Random();
int firstRoll = r.nextInt(6);
int secondRoll = r.nextInt(6);
firstRoll+= 1;
secondRoll+= 1;
int timesWin = 0;
int timesLose = 0;
int sumOfdice = firstRoll + secondRoll;
do
{
System.out.println("Die 1: "+ firstRoll);
System.out.println("Die 2: "+ secondRoll);
System.out.println("total: "+ sumOfdice);
if(sumOfdice == 4 || sumOfdice == 6 || sumOfdice == 8 || sumOfdice == 10)
{
System.out.println("Win");
timesWin++;
}
if(sumOfdice == 3 || sumOfdice == 5 || sumOfdice == 7 || sumOfdice == 9 || sumOfdice == 11)
{
System.out.println("Lose");
timesLose++;
}
else
{
System.out.println("Play Again");
}
} while(sumOfdice == 12 || sumOfdice ==2);
System.out.println("You won " + timesWin + "times");
System.out.println("You lost " + timesLose + "times");
}
}
What I expected was rolling again should only applies to when sum of dice is 2 or 12 but I get infinite loops. Please help me if you know the answer.

sumOfdice should be assigned a new value in the loop
in the else statement you should re roll the dices
...
else{
System.out.println("Play Again");
firstRoll = r.nextInt(6);
secondRoll = r.nextInt(6);
sumOfdice = firstRoll + secondRoll;
}
...
otherwise the while() will loop over the same value.

Related

Java dice game not correctly playing subsequent rounds of the game: boolean variable issue?

I've been working on a dice game and finally got it to work (by that, I mean I got the .class file to generate). However, there is something wrong with the logic of the game that I can't figure out. I think the program is interpreting the rules of the game wrong.
Here are the rules: A player rolls four dice for one round. In this first round,
if the sum of the dice rolls equals a 6, 12, 13, 17, 19, or 23 the player wins and the game ends. If the player rolls a 9, 11, 18, or 24 on this round, the player loses. If the player rolls any other number, the sum of the dice becomes the "goal number" and the game keeps rolling the dice.
The player must continue to roll the dice again until they roll a 23 and lose, or roll the sum of the dice from the first round again, and then wins.
When I run the game, it keeps using the rules from the first round, although the rules change for the subsequent rounds.
For example, here's one of the outputs I've gotten from the console
Your sum of the dice values: 15. You rolled a sum of 15, so the game will keep playing until you roll this sum again.(and then the second round rolls) Your sum of the dice values: 17. You win!
Clearly this isn't right, because in this case you can only win if you roll a 15 again. It's clearly still using the winning values from the first time, which I don't understand because I have the do-while loop for the second round under the conditions keepPlaying = true and justOneRound = false, but it's still not acknowledging that justOneRound is false for the subsequent rounds.
Here is the code, (I know this sounds confusing but hopefully it makes sense once you see this):
// Declare boolean variables to tell if the user keeps playing in subsequent rounds (to be used by multiple methods).
public static boolean justOneRound = false;
public static boolean keepPlaying = true;
// Declare variables for the goal number and the sum of the dice on the first round.
public static int firstRoundDiceSum = 0;
// main method header
public static void main (String [] args)
{
// Play the game for at least one round, and then again if the user doesn't win or lose.
do
{
// Roll the dice (redirect to the roll() method) and declare a variable to hold the sum of the values that have returned.
firstRoundDiceSum = roll();
// Print the sum of the rolled dice.
System.out.println("Your sum of the dice values: ");
System.out.println(firstRoundDiceSum);
// Determine if the user won or not.
if (firstRoundDiceSum == 6 ||firstRoundDiceSum == 12 ||firstRoundDiceSum == 13 ||firstRoundDiceSum == 17 || firstRoundDiceSum == 19 ||firstRoundDiceSum == 23)
{
justOneRound = true;
keepPlaying = false;
System.out.println("You win!");
System.exit(0);
}
else if (firstRoundDiceSum == 9 ||firstRoundDiceSum == 11 ||firstRoundDiceSum == 18 ||firstRoundDiceSum == 24)
{
justOneRound = true;
keepPlaying = false;
System.out.println("You lose!");
System.exit(0);
}
else
{
justOneRound = false;
keepPlaying = true;
System.out.println("You rolled a sum of: " + firstRoundDiceSum + ", so the game will keep playing until you roll this sum again.");
}
} while (justOneRound = true);
// Play the game for subsequent rounds until the user gets the goal number or loses.
do
{
// Roll the dice (redirect to the roll2() method) and declare a variable to hold the sum of the values that have returned.
int laterRoundsDiceSum = roll2();
// Print the sum of the rolled dice.
System.out.println("Your sum of the dice values: ");
System.out.println(laterRoundsDiceSum);
// Determine if the user won or not.
if (laterRoundsDiceSum == firstRoundDiceSum)
{
keepPlaying = false;
System.out.println("You win!");
System.exit(0);
}
else if (laterRoundsDiceSum == 23)
{
keepPlaying = false;
System.out.println("You lose!");
System.exit(0);
}
else
{
keepPlaying = true;
System.out.println("You didn't roll " + firstRoundDiceSum + ", so you have to keep rolling until you get it!");
}
} while ((justOneRound = false) && (keepPlaying = true));
}
// roll() method header that rolls the die for the first round (creates a dieRoll object and gets a random value for the die).
public static int roll()
{
do
{
// Create a random class object.
Random dieRoll = new Random();
// Declare a variable for the sum, and set it to zero before the dice roll.
int firstRoundDiceSum = 0;
// Use a for-loop to roll the dice four times (with counter variable timesRolled).
for (int timesRolled = 1; timesRolled <= 5; timesRolled ++)
{
int dieValue = dieRoll.nextInt(6) + 1;
firstRoundDiceSum = firstRoundDiceSum + dieValue;
}
return firstRoundDiceSum;
} while (justOneRound = true);
}
// roll() method header that rolls the die for the subsequent round(s) (creates a dieRoll object and gets a random value for the die).
public static int roll2()
{
do
{
// Create a random class object.
Random dieRoll = new Random();
// Declare a variable for the sum, and set it to zero before the dice roll.
int laterRoundsDiceSum = 0;
// Use a for-loop to roll the dice four times (with counter variable timesRolled).
for (int timesRolled = 1; timesRolled <= 5; timesRolled ++)
{
int dieValue = dieRoll.nextInt(6) + 1;
laterRoundsDiceSum = laterRoundsDiceSum + dieValue;
}
return laterRoundsDiceSum;
} while (justOneRound = true);
}
}

Storing Random Numbers in an Array

I am a bit confused on how I would take the randomly generated number in a range from my program, store that into an array, and read and print out from the array how many times that the number was generated.
For the random import I am using java.util.concurrent.ThreadLocalRandom;
public static void main(String[] args) {
char quitOption = 'q';
char continueOption = 'c';
char input;
int[] myArray;
Scanner console = new Scanner(System.in);
do {
int roll = ThreadLocalRandom.current().nextInt(1, 6);
System.out.println("Roll is " + roll);
System.out.println("Enter c to continue or enter q to quit ");
input = console.nextLine().charAt(0);
if (input == continueOption || input == 'C') {
roll = ThreadLocalRandom.current().nextInt(1, 6);
System.out.println("Roll is " + roll);
System.out.println("Enter c to continue or enter q to quit ");
input = console.nextLine().charAt(0);
} else if (input == quitOption || input == 'Q') {
System.exit(0);
}
} while (continueOption == 'c' || continueOption == 'C');
}
I would use a HashMap<Integer, Integer> lets call it rollMap.
Each time you roll you get int currentRoll = randomRoll().
If I were you, I would then say:
if(rollMap.containsKey(currentRoll)){
rollMap.put(currentRoll, rollMap.get(currentRoll) + 1);
}else{
rollMap.put(currentRoll, 1);
}
You can then get how many times each number was rolled by saying:
System.out.println(rollMap.get(<rollid>));
You must figure out how to overcome two problems:
Figure out how many rolls there will be, as Array's are fixed sized
Count how many time a number is rolled
You could use a List, and then use built in methods such as Collections.frequency, or if you are confined to an Array, check to make sure that adding another number will not be out of bounds, (And if it will be then copying it to a new Array) and then iterating over the Array and counting how many times each number occurs.
However, we know the range of numbers that will occur. So why not initialize an Array with six elements, and let 0 be 1, 1 be 2, and so on. Then every time that number is rolled, we increment the index of the respective number. So something like:
int roll = ThreadLocalRandom.current().nextInt(1, 6);
arr[roll -1]++;
So if a two is rolled, we will add one to the 1th index:
[0, 1, 0, 0, 0, 0]
And so on. Then when you need to count the index its a simple loop:
for(int i = 0; i < arr.length; i++) {
System.out.println(i + 1 + " occurs: " + arr[i] + " times");
}
Also you are over complicating your loop. It can be simplified to:
char input;
int[] myArray = new int[6];
Scanner console = new Scanner(System.in);
do {
int roll = ThreadLocalRandom.current().nextInt(1, 6);
System.out.println("Roll is " + roll);
myArray[roll -1]++;
System.out.println("Enter c to continue or enter q to quit ");
input = console.nextLine().charAt(0);
} while (input == 'c' || input == 'C');
for(int i = 0; i < myArray.length; i++ ) {
System.out.println(i + 1 + " occurs: " + myArray[i] + " times");
}
Sample run:
Roll is 4
Enter c to continue or enter q to quit
c
Roll is 1
Enter c to continue or enter q to quit
c
Roll is 3
Enter c to continue or enter q to quit
c
Roll is 3
Enter c to continue or enter q to quit
c
Roll is 1
Enter c to continue or enter q to quit
c
Roll is 1
Enter c to continue or enter q to quit
q
1 occurs: 3 times
2 occurs: 0 times
3 occurs: 2 times
4 occurs: 1 times
5 occurs: 0 times
6 occurs: 0 times

Calculate the Probability of winning (wins/ (wins + losses)) with 10,000 simulations in the game of craps.. this is part of an assignment

Calculate the Probability of winning (wins/ (wins + losses)) using 10,000 simulations in the game of craps. Here is the method for the game of craps:
public class CrapsGame {
public static void main(String[] args) {
int dice1 = (int)(Math.random()* 6) + 1;
int dice2 = (int)(Math.random()* 6) + 1;
int roll = dice1 + dice2;
System.out.println();
System.out.print("You rolled "+roll+". ");
if(roll == 2 || roll == 3 || roll == 12){
System.out.println("You Lose !");
}else if(roll == 7 || roll == 11){
System.out.println("You Win !");
}else{
System.out.println("Point is "+roll+"\n");
dice1 = (int)(Math.random()* 6) + 1;
dice2 = (int)(Math.random()* 6) + 1;
int roll2 = dice1 + dice2;
System.out.print("You rolled "+roll2+". ");
while(roll2 != 7){
if(roll == roll2){
System.out.println("You Win !");
break;
}else{
System.out.println("Point is "+roll+"\n");
}
dice1 = (int)(Math.random()* 6) + 1;
dice2 = (int)(Math.random()* 6) + 1;
roll2 = dice1 + dice2;
System.out.print("You rolled "+roll2+". ");
}
if(roll2 == 7){
System.out.println("You Lose !");
}
}
}
}
I don't think this should be difficult, I just need code to run 10,000 simulations and then also calculating the probability. Thank you :)
Would it be possible to have someone insert a working version of this
Putting a while or for loop outside of the logic and creating 2 counters (timesWinning, timesLosing). Incrementing each according, inside the existing code. After the loop runs 10.000 times, do the math as needed: wins/ (wins + losses)
thank you this is part of an assignment
And you should modify his code to this at the end:
System.out.println("Probability of winning: " + ((double)timesWon/(timesWon + timesLost)));
I got this as a result from my own:
You played: 10000.0, won: 5078, probability of winning : 0.5078
You played: 1.0E8, won: 50707214, probability of winning : 0.50707214
Your code has already all the logic needed. To repeat it as many times you want, there are different ways. They are known as loops. If you search on Google you will find for, while, do/while and some others (you have a while already inside the code).
For your question, the basic would be to repeat it 10,000 times the same things.
public class CrapsGame {
public static void main(String[] args) {
// Create some variables to control the times it won and times it lost
int timesWon = 0;
int timesLost = 0;
// Here we're saying it's gonna repeat 10000 times, incrementing 1 by 1
for(int i=0; i<10000; i++) {
// Here you will insert all the existing logic from your program
// In the existing code, increment the variables declared according
if(roll == 2 || roll == 3 || roll == 12){
System.out.println("You Lose !");
timesLost++;
}else if(roll == 7 || roll == 11){
System.out.println("You Win !");
timesWon++;
}else{
// Where you find it won, insert `timesWon++;`
// Where you find it lost, insert `timesLost++;`
}
}
// Here it exits the for loop (after 10000 times)
// Here's where you can calculate
System.out.println("Probability of winning: " + (timesWon/(timesWon + timesLost)));
}
}
This should be sufficient to get the desired result.
Hope it helps.

Program complies, but while not finish second half. Yahtzee Die based program, Java

Created a program that rolls 5 6 sided dice. I repeat this until a yahtzee. I also keep track of the number of rolls, and I repeat the entire process 1000x. My program works, but does not display anything. Please help me to spot the error thank you. In my last for-loop, when i run the program there is no output display after it? Why?
import java.util.Scanner;
/* The DiceTester class simulates the rolling of dice */
public class DiceTester
{
public static void main(String[] args)
{
int userInput; //Holds user input.
int sumDice; //Holds the sum of the dice.
int firstDie; //Holds value of die 1.
int secondDie; //Holds value of die 2.
Scanner keyboard = new Scanner(System.in); //scanner object for input.
//Prompt and collect user input.
System.out.print("Creating two dice. One with 6 sides, enter value for
the second die: ");
userInput = keyboard.nextInt();
//Create two dice objects.
Die die1 = new Die(); //With default constructor.
Die die2 = new Die(userInput); //With argument.
System.out.println("Generating dice ...");
System.out.println(die1); //Show state of dice, toString.
System.out.println(die2);
System.out.println("Rolling the dice ...");
//Roll Dice. Store value of indiviual dice and sum.
die1.roll();
die2.roll();
firstDie = die1.getValue();
secondDie = die2.getValue();
sumDice = firstDie + secondDie;
//Display values to screen.
System.out.println(firstDie + " " + secondDie + " " + sumDice);
System.out.println("\nDie1 Die2 Sum");
System.out.println("-------------");
//Create for loop that runs 10x and shows value of dice.
for (int roll = 1; roll <= 10; roll++)
{
die1.roll();
die2.roll();
firstDie = die1.getValue();
secondDie = die2.getValue();
sumDice = firstDie + secondDie;
System.out.println(firstDie + " " + secondDie + " " +
sumDice);
}
System.out.println("\nGenerating five 6-sided dice ...");
//Creating 5 more dice.
Die yahtDie = new Die();
Die yahtDie2 = new Die();
Die yahtDie3 = new Die();
Die yahtDie4 = new Die();
Die yahtDie5 = new Die();
//Print state of dice.
System.out.println(yahtDie + "\n" + yahtDie2 + "\n" + yahtDie3 + "\n" +
yahtDie4 + "\n" + yahtDie5);
int numRoll = 0; //Holds the number of rolls until yahtzee.
int totalRoll = 0; //Holds the total number of rolls to get yahtzee.
double avgRoll; //Holds the average number of rolls to get yahtzee.
int maxRoll = 0; //Holds the maximum number of rolls, yahtzee
int minRoll = 0; //Holds the minimum number of roll, yahtzee
//Create for loop to iterate 1000x.
for (int roll = 1; roll <= 1000; roll++)
{
//Roll dice in while loop.
while(!(yahtDie == yahtDie2 || yahtDie2 == yahtDie3 || yahtDie3 ==
yahtDie4 || yahtDie4 == yahtDie5))
{
yahtDie.roll();
yahtDie2.roll();
yahtDie3.roll();
yahtDie4.roll();
yahtDie5.roll();
numRoll++;
}
totalRoll += numRoll;
if (maxRoll > numRoll)
maxRoll = numRoll;
if (minRoll < numRoll)
minRoll = numRoll;
}
avgRoll = totalRoll / 1000.0; //Total number of rolls to get yahtzee /
number of yahtzees.
System.out.println("Rolling for 1000 yahtzees... \nCounting the number
of rolls for 1000 yahtzees... \nFound 1000 yahtzees.");
System.out.println("The maximum amount of rolls to get a yahtzee: " +
maxRoll);
System.out.println("The minimum amount of rolls to get a yahtzee: " +
minRoll);
System.out.println("The average amount of rolls to get a yahtzee: " +
avgRoll);
}
}
Output:
Creating two dice. One with 6 sides, enter value for the second die: 5
Generating dice ...
Die[6 sides, value = 2]
Die[6 sides, value = 4]
Rolling the dice ...
4 1 5
Die1 Die2 Sum
-------------
2 6 8
5 6 11
4 2 6
5 3 8
1 3 4
4 6 10
6 6 12
6 5 11
6 5 11
2 1 3
Generating five 6-sided dice ...
Die[6 sides, value = 5]
Die[6 sides, value = 1]
Die[6 sides, value = 3]
Die[6 sides, value = 5]
Die[6 sides, value = 6]
die class:
import java.util.Random;
/* This class creates a die of n sides and rolls it. */
public class Die
{
private int numSides; //holds the amount of sides of dice.
private int faceUp; //holds the value of the die facing up.
/* Default constructor creates a 6 sided die and rolls it. */
public Die()
{
//Random newDie = new Random(); //Create random object for the dice.
numSides = 6;
roll(); //Assign the value from the random newDice method (1-6) to the current side up.
}
/* This constructor creates a die of 4, 6, 8, 10, 12, 20, or 100 sides, and rolls it. */
public Die(int side)
{
//Random newDie = new Random();
if (side == 4 || side == 6 || side == 8 || side == 10 || side == 12 || side == 20 ||
side == 100)
{
numSides = side;
roll();
}
else
{
numSides = 6;
roll();
}
}
/* The getValue method returns the the current value facing up. */
public int getValue()
{
return faceUp;
}
/* This method rolls the dice */
public void roll()
{
Random newDie = new Random(); //Create random object for the dice.
faceUp = newDie.nextInt(numSides) + 1; //Assigns random value from 1 to numSides to faceUp. "Simulate dice roll."
}
/* This method prints the state of the object. */
public String toString()
{
return "Die[" + numSides + " sides, value = " + faceUp + "]";
}
}

How come my if else statements don't execute?

First of all, I have found two other threads that have similar questions. There problem is that they didn't use the right equal sign for string and not formatting the if statements correctly for their particular problem.
For my assignment, I need to create a game called Pig where the player verses a computer in getting 100 points first in rolling pairs of dice. If the player rolls 1 on one turn, they get no additional points. If the player rolls two 1's, then they lose all their points. I have not coded the computer's turn yet, just focusing on the player. Please tell me what I am doing wrong. Thank you very much in advance.
import java.util.Scanner;
public class FourFive
{
public static void main (String[] args)
{
Pigs myopp = new Pigs();
Scanner scan = new Scanner (System.in);
final int Round = 20;
int num1, num2;
int roundTotal = 0;
int playerTotal = 0;
int compTotal = 0;
int win = 100;
int turnOver = 1;
Pigs die1 = new Pigs();
Pigs die2 = new Pigs();
String play = "y";
System.out.println("Type y to play");
play = scan.nextLine();
while (play.equalsIgnoreCase("y"))
{
for (int roll = 1; roll <= 6; roll++)//Each die has 6 sides
{
num1 = die1.roll();//rolls first die
num2 = die2.roll();//rolls second die
int points = num1 + num2;// adds dies up to get total for this turn
System.out.println("You roll " + num1 + " and " + num2);
if (num1 == 1 || num2 == 1)//If either of the dies roll 1, no points
points += 0;
else if (num1 == 1 && num2 == 1)//if both are 1, lose ALL points
playerTotal = 0;
else
System.out.println("you earned " + points + " this round");
playerTotal += points; total number of points per round added
System.out.println("You have a total of " + playerTotal);
System.out.println("Type y to play");
play = scan.nextLine();
}
}
}
}
My Output:
Type y to play
y
You roll 4 and 2
you earned 6 this round
You have a total of 6
Type y to play
y
You roll 6 and 5
you earned 11 this round
You have a total of 17
Type y to play
y
You roll 1 and 1
You have a total of 19 //total should be 0 because of the two 1's
Type y to play
y
You roll 6 and 3
you earned 9 this round
You have a total of 28
Type y to play
y
You roll 1 and 1
You have a total of 30 //total should be 0 because of the two 1's
Type y to play
y
You roll 6 and 4
you earned 10 this round
You have a total of 40
Type y to play
y
You roll 5 and 2
you earned 7 this round
You have a total of 47
Type y to play
y
You roll 5 and 1
You have a total of 53 //shouldn't add any additional points because of the "1"
Type y to play
If num1 is 1, then the first if condition takes it. It will not check the 'else if' condition. Similarly, if num2 is 1, the if condition takes it. So put your && condition first.
if (num1 == 1 && num2 == 1)//if both are 1, lose ALL points
playerTotal = 0;
else if (num1 == 1 || num2 == 1)//If either of the dies roll 1, no points
points += 0;
else
System.out.println("you earned " + points + " this round");
Your if logic is flawed and a bit redundant. Try this:
if (num1 == 1 && num2 == 1) {
playerTotal = 0;
}
else if (num1 != 1 && num2 != 1) {
playerTotal += points;
System.out.println("you earned " + points + " this round");
}
System.out.println("You have a total of " + playerTotal);

Categories