Make Math.Random loop until specific number is reached - java

I'm trying to make a program that 'rolls two dice' and combines the number and needs to keep going until a specific number is reached 7 or 11 but every time I run it it keeps going forever.
double total = 0;
while (total != 7 || total != 11) {
DecimalFormat x = new DecimalFormat("#");
double dice1 = Math.random() * 6 + 1;
double dice2 = Math.random() * 6 + 1;
double total = (dice1 + dice2);
System.out.println("Dice 1: " + x.format(dice1) + " Dice 2: " + x.format(dice2) + " Total: " + x.format(total));
}
I think its because the int total is set to 0 and isn't getting the total from the loop but how can i fix this?

Your while loop logic is not correct. The total will always not be 7 or not be 11. You want "and" instead, using &&. Change
while (total != 7 || total != 11) {
to
while (total != 7 && total != 11) {
Also, I don't know of any dice that yield non-integers, so I would cast the results to int and declare dice1, dice2, and total as ints.

It's because you shadow total and you need to test logical and (not or). I would also prefer to use Random and nextInt(int) like
int total = 0; // <-- don't shadow me.
Random rand = new Random();
while (total != 7 && total != 11) {
int dice1 = rand.nextInt(6) + 1; // <-- using rand.
int dice2 = rand.nextInt(6) + 1;
total = (dice1 + dice2); // <-- no double.
System.out.printf("Dice 1: %d Dice 2: %d Total: %d%n", dice1, dice2, total);
}

You need an AND instead of an OR. And try it with int:
int total = 0;
while (total != 7 && total != 11) {
Random rand = new Random();
int dice1 = rand.nextInt((6 - 1) + 1) + 1;
int dice2 = rand.nextInt((6 - 1) + 1) + 1;
total = (dice1 + dice2);
System.out.println("Dice 1: " + dice1 + " Dice 2: " +dice2 + " Total: " + total);

Related

How to count the number of time sum is = 7?

I have to make program to roll 2 dice 100 times, and count the # of time the sum equals 7.
I tried doing a count for loop to count the sums = 7, but think I'm getting off base somewhere in the logic of that.
// int i = 0; No. of rolls
// int count = 0; No. of rolls = to 7
for (int i = 0; i <= 100; i++){
int dice1 = randomGenerator.nextInt(7);
int dice2 = randomGenerator.nextInt(7);
int sum = (dice1 + dice2);
System.out.println(dice1 + ", " + dice2 + ", total: " + sum + " roll: " + i);
}
for (int count = 0; count++) {
System.out.println(count);
}
System.out.println("Total number of time sum equaled 7 was " + count);
I'm getting the random rolls, roll count, and sum of dice correctly, Just need to figure out how to add a sum = 7 count and I'm getting stuck.
Here's another answer using streams
public static void main(String[] args){
Random rng = new Random();
long result = IntStream
.generate(() -> rng.nextInt(6) + rng.nextInt(6) + 2)
.limit(100)
.filter(x -> x == 7)
.count();
System.out.println("Total number of time sum equaled 7 was " + result);
}
Just replace your for (int count = 0; count++) { ... } with if (sum==7) count++ and put it after int sum = (dice1 + dice2);
This increases count if the sum is 7 within the loop of your 100 double dice rolls.
To remove the wrong dice range (0-7, see comment #Robby Cornelissen) just do a randomGenerator.nextInt(6)+1.
int count = 0; // No. of rolls = to 7
for (int i = 0; i <= 100; i++){
int dice1 = randomGenerator.nextInt(6)+1;
int dice2 = randomGenerator.nextInt(6)+1;
int sum = (dice1 + dice2);
if (sum==7) count++;
System.out.println(dice1 + ", " + dice2 + ", total: " + sum + " roll: " + i);
}
System.out.println("Total number of time sum equaled 7 was " + count);
Using Java 8, program would look like this :
public class Dice
{
static int count = 0;
static Random ran = new Random();
public static void main(String[] args)
{
IntStream.rangeClosed(1, 100). // iterates 1 to 100
parallel().// converts to parallel stream
forEach(i -> {
rollDiceAndCheckIfSumIs7();
});// prints to the console
System.out.println("Out of 100 times, total number of times, sum was 7 is :" + count);
}
private static void rollDiceAndCheckIfSumIs7()
{
int dice1 = ran.nextInt(7);
int dice2 = ran.nextInt(7);
count += (dice1 + dice2 == 7) ? 1 : 0;
}
}

In java, how do I make the while loop run until the condition is satisfied multiple times?

I am trying to make a program where the user can input the target as well as the amount of times he wants to hit the target. The problem is that I dont know how to make the while loop run more than once (satisfy the condition more than one time).
Scanner target = new Scanner(System.in);
System.out.println("Enter dice target (1-10):");
int targetNumber = target.nextInt();
Scanner required = new Scanner(System.in);
System.out.println("Enter the number of required matches: ");
int requiredMatches = target.nextInt();
int number = (int) (1 + 10 * Math.random());
int sum = 1;
if (targetNumber > 10) {
System.out.println("Error");
}
else {
while (number != targetNumber) {
System.out.println("Your number is " + number);
number = (int) (1 + 10 * Math.random());
++sum;
}
System.out.println("You reached your target " + requiredMatches + " times in " + sum + " tries.");
}
The code lets me match the target only once, but I want it to be able to obtain the target value [RequiredMatches] times before it stops.
If the number matches, then reduce the tries by 1.
Scanner Required = new Scanner(System.in);
System.out.println("Enter the number of required matches: ");
int RequiredMatches = Target.nextInt();
int Number = (int) (1 + 10 * Math.random());
int sum = 1;
if (NumberTarget > 10) {
System.out.println("Error");
} else {
while ((Number != NumberTarget) || (RequiredMatches > 0)) {
System.out.println("Your number is " + Number);
Number = (int) (1 + 10 * Math.random());
++sum;
if (Number==NumberTarget) {
RequiredMatches--;
}
System.out.println("You reached your target " + RequiredMatches + " times in " + sum + " tries.");
}
}

How do I simulate 3000 dice rolls and count the number of times doubles are rolled? JAVA

I'm new to the programming world so I'd deeply appreciate if any of you could help me become better at this. My goal for this program is to simulate 3000 dice rolls and count the number of times doubles are rolled for each of the different possible pairs of doubles using a while loop. The results should be printed out in a dialog box.
Random random;
random = new Random();
diceRolls = 1;
snakeEyes = 1;
doubleTwos = 1;
doubleThrees = 1;
doubleFours = 1;
doubleFives = 1;
doubleSixes = 1;
while (diceRolls <= finalDiceRoll) {
int diceRolls = 1;
int die1 = random.nextInt(6) + 1;
int die2 = random.nextInt(6) + 1;
if (die1 == 1 && die2 == 1){
//snakeEyes = snakeEyes + 1;
snakeEyes++;
}
else if (die1 == 2 && die2 == 2 ) {
doubleTwos++;
}
else if (die1 == 3 && die2 == 3) {
doubleThrees++;
}
else if (die1 == 4 && die2 == 4) {
doubleFours++;
}
else if (die1 == 5 && die2 == 5) {
doubleFives++;
}
else if (die1 == 6 && die2 == 6) {
doubleSixes++;
}
JOptionPane.showMessageDialog (null, "You rolled snake eyes " + snakeEyes + " times\nYou rolled double twos " + doubleTwos + " times\nYou"
+ " rolled double threes " + doubleThrees + " times\nYou rolled double fours " + doubleFours + " times\nYou"
+ " rolled double fives " + doubleFives + " times\nYou rolled double sixes " + doubleSixes + " times");
}
The issue i'm having here is that the results i'm getting from the program don't seem "plausible". For example, out of 3000 dice rolls, I get 1 pair of each double. What am I doing wrong?
Few changes you have to make in your code,
1. Initialize all your variables by 0.
2. change while-loop condition to
while (diceRolls <= finalDiceRoll) // hoping that finalDiceRoll = 3000
3 remove int diceRolls = 1; from while-loop and add diceRolls++; at end of while-loop.
4. Put your JOptionPane outside while-loop. if not you have to close 3000 time your JOptionPane dailog.
After applying these changes to your code you will learn what have you done wrong and your code will run fine.
Move the showMessageDialog outside of the while loop and increment the diceRolls variable. Initialize all other integer variables with 0.
A better (cleaner and shorter) approach would be to use a two-dimensional array or a map.
Random random = new Random();
int snakeEyes = 0;
int doubleTwos = 0;
int doubleThrees = 0;
int doubleFours = 0;
int doubleFives = 0;
int doubleSixes = 0;
int diceRolls = 1;
while (diceRolls <= 3000) {
int die1 = random.nextInt(6) + 1;
int die2 = random.nextInt(6) + 1;
if (die1 == 1 && die2 == 1) {
snakeEyes++;
} else if (die1 == 2 && die2 == 2) {
doubleTwos++;
} else if (die1 == 3 && die2 == 3) {
doubleThrees++;
} else if (die1 == 4 && die2 == 4) {
doubleFours++;
} else if (die1 == 5 && die2 == 5) {
doubleFives++;
} else if (die1 == 6 && die2 == 6) {
doubleSixes++;
}
diceRolls++;
}
JOptionPane.showMessageDialog(null, "You rolled snake eyes " + snakeEyes + " times\nYou rolled double twos " + doubleTwos + " times\nYou"
+ " rolled double threes " + doubleThrees + " times\nYou rolled double fours " + doubleFours + " times\nYou"
+ " rolled double fives " + doubleFives + " times\nYou rolled double sixes " + doubleSixes + " times");
The above-mentioned shorter version:
Random random = new Random();
int[] doubled = new int[6];
for (int diceRolls = 0; diceRolls < 3000; diceRolls++) {
int die1 = random.nextInt(6);
int die2 = random.nextInt(6);
if (die1 == die2)
doubled[die1]++;
}
JOptionPane.showMessageDialog(null, "You rolled snake eyes " + doubled[0] + " times\nYou rolled double twos " + doubled[1] + " times\nYou"
+ " rolled double threes " + doubled[2] + " times\nYou rolled double fours " + doubled[3] + " times\nYou"
+ " rolled double fives " + doubled[4] + " times\nYou rolled double sixes " + doubled[5] + " times");
The counting logic should go as follows:
doubleTwos = 0;
doubleThrees = 0;
doubleFours = 0;
doubleFives = 0;
doubleSixes = 0;
finalDiceRoll = 3000;
int diceRolls = 0;
while (diceRolls < finalDiceRoll) {
++diceRolls;
With any message after the loop.
With an array you may save typing:
int[] doubleCounts = new int[6]; // By 0 based dice values
for (int i = 0; i < finalDiceRoll; ++i) {
int die1 = random.nextInt(6); // With dice values 0-5
int die2 = random.nextInt(6);
if (die1 == die2) {
++doubleCounts[die1];
}
}
int snakeEyes = doubleCounts[0];
int doubleTwos = doubleCounts[1];
...
Simplify. Eliminate duplications. Don't use multiple variables when you can use an array.
int[] doubles = new int[7]; // make the index the number rolled (ignore index 0)
int diceRolls = 0;
while (diceRolls++ < 3000) {
int die1 = random.nextInt(6) + 1;
int die2 = random.nextInt(6) + 1;
if (die1 == die2)
doubles[die1]++;
}
String output = "";
for (int i = 1; i <= 6; i++)
output += "You rolled double " + i + "'s " + doubles[i] + " times\n";
JOptionPane.showMessageDialog (null, output);
That's all you need.

Craps game: How do i get the while loop in this code from going into an infinite loop?

this are comments that explain the game so you can test it, but the main problem is when you are suppose to run the while loop if you a point value then it becomes an infinite loop. How do I get it to not be an infinite loop?
import java.util.Random;
public class Craps {
private int roll1;
private int roll2;
private Random randGen;
private int sum;
private int thePoint = sum;
private int bet;
private int newSum;
// instance classes
public Craps() {
randGen = new Random(); // this is the random generator
}
// when you win you double your money
// when you lose you lose everything
public void roll(int bet) { // you can bet as much money as you want
roll1 = (randGen.nextInt(6) + 1);
roll2 = (randGen.nextInt(6) + 1);
sum = roll1 + roll2; // you must add the two rolls and that is your sum
if (sum == 2 || sum == 3 || sum == 12) { // if the sum is 2 you lose
System.out.println("The sum is 2. You Lose!");
System.out.println("Your credit:" + " " + bet * 0);
} else if (sum == 7 || sum == 11) { // if it 7 you win
System.out.println("The sum is 7. You Win!");
System.out.println("Your credit:" + " " + bet * 2);
} else {
System.out.println("You rolled a" + " " + sum + ". " + "That is your point. Roll again.");
sum = thePoint;
}
}
public void rollAgain() {
while (sum != 7 || sum != thePoint) { // whatever the the sum is that is not one of the numbers above becomes your point.
roll1 = (randGen.nextInt(6) + 1);// you must role the die again until you get your point again the you win or until you get a 7 and then you lose.
roll2 = (randGen.nextInt(6) + 1);
sum = roll1 + roll2;
if (thePoint == sum) { // if the point equals the sum you win
System.out.println("You're on point. You Win!");
System.out.println("Your credit:" + " " + bet * 2);
} else if (sum == 7) { // if it equals 7 you lose.
System.out.println("You got a 7. You lose!");
System.out.println("Your credit:" + " " + bet * 0);
}
}
}
}
You need to change your loop condition.
while (sum != 7 || sum != thePoint) what happens here is that as soon as the first condition is met (sum is not seven), the loop starts executing.
if you change it to while (sum != 7 && sum != thePoint) then both these conditions need to be met - the loop only starts executing again if sum is not seven or the value of thePoint.

Finding probability using nested for loops in Java

My problem is that whenever I try to compile and run my program, it says one of my arithmetic problems closer to the end of my code is dividing by zero. Now there is another problem. Whenever the user is prompted to enter the number of rolls, you can input a number and hit enter, but it just skips to the next line and nothing happens. Nothing else in the code happens.
* NOTE *
I can't use arrays in this assignment because it is not covered until the next section.
Here is my assignment here. This is what i'm supposed to be doing. I can't figure out what is going wrong here. My math seems to be correct but something is going wrong.
In short my assignment wants me to find the probability of two 11 sided dice being "rolled" the amount of times the user inputs. For example:
If the user says the dice it to be rolled 100 times it would output it something like this
2s: (insert Probability of having the sum of the 2 dice being 2 after 100 rolls)
3s: (insert Probability of having the sum of the 2 dice being 3 after 100 rolls)
4s: (insert Probability of having the sum of the 2 dice being 4 after 100 rolls)
5s: (insert Probability of having the sum of the 2 dice being 5 after 100 rolls)
and so on.
Here is my code so far:
public static void main(String[] args)
{
//Declare and initialize variables and objects
Scanner in = new Scanner(System.in);
Random randNum = new Random();
int match = 0; //Number of times sum of dice matches the current sum
int die1 = 0; //Random generated numbers
int die2 = 0;
int diceTotal2 = 0;
int diceTotal3 = 0;
int diceTotal4 = 0;
int diceTotal5 = 0;
int diceTotal6 = 0;
int diceTotal7 = 0;
int diceTotal8 = 0;
int diceTotal9 = 0;
int diceTotal10 = 0;
int diceTotal11 = 0;
int diceTotal12 = 0;
int sumOfDice = 0;
double probability2 = 0.0;
double probability3 = 0.0;
double probability4 = 0.0;
double probability5 = 0.0;
double probability6 = 0.0;
double probability7 = 0.0;
double probability8 = 0.0;
double probability9 = 0.0;
double probability10 = 0.0;
double probability11 = 0.0;
double probability12 = 0.0;
//Input: ask user for number of rolls and number of sides on a die
System.out.println("Number of Rolls: ");
int rolls = in.nextInt();
//***************************************************************************************
//Using nested loops, cycle through the possible sums of the dice.
//Roll the dice the given number of times for each sum.
//Count how many times the sum of the dice match the current sum being looked for.
//***************************************************************************************
//Loop to increment through the possible sums of the dice
//Loop to throw dice given number of times
for( int numberOfRolls = 1; numberOfRolls < rolls; numberOfRolls++)
{
die1 = randNum.nextInt(6);
die2 = randNum.nextInt(6);
sumOfDice = die1 + die2;
for( ; ; )
{
//Check if the sum of dice is equal to the given sum
if(sumOfDice == 2)
{
diceTotal2++;
probability2 = diceTotal2 / numberOfRolls;
}
else if(sumOfDice ==3)
{
diceTotal3++;
probability3 = diceTotal3 / numberOfRolls;
}
else if(sumOfDice ==4)
{
diceTotal4++;
probability4 = diceTotal4 / numberOfRolls;
}
else if(sumOfDice ==5)
{
diceTotal5++;
probability5 = diceTotal5 / numberOfRolls;
}
else if(sumOfDice ==6)
{
diceTotal6++;
probability6 = diceTotal6 / numberOfRolls;
}
else if(sumOfDice ==7)
{
diceTotal7++;
probability7 = diceTotal7 / numberOfRolls;
}
else if(sumOfDice ==8)
{
diceTotal8++;
probability8 = diceTotal8 / numberOfRolls;
}
else if(sumOfDice ==9)
{
diceTotal9++;
probability9 = diceTotal9 / numberOfRolls;
}
else if(sumOfDice ==10)
{
diceTotal10++;
probability10 = diceTotal10 / numberOfRolls;
}
else if(sumOfDice ==11)
{
diceTotal11++;
probability11 = diceTotal11 / numberOfRolls;
}
else if(sumOfDice ==12)
{
diceTotal12++;
probability12 = diceTotal12 / numberOfRolls;
}
}
}
System.out.println("Sum of Dice" + " " + "Probability");
System.out.println("2s: \t\t" + probability2 + "%");
System.out.println("3s: \t\t" + probability3 + "%");
System.out.println("4s: \t\t" + probability4 + "%");
System.out.println("5s: \t\t" + probability5 + "%");
System.out.println("6s: \t\t" + probability6 + "%");
System.out.println("7s: \t\t" + probability7 + "%");
System.out.println("8s: \t\t" + probability8 + "%");
System.out.println("9s: \t\t" + probability9 + "%");
System.out.println("10s: \t\t" + probability10 + "%");
System.out.println("11s: \t\t" + probability11 + "%");
System.out.println("12s: \t\t" + probability12 + "%");
//After all throws, calculate percentage of throws that resulted in the given sum
} //end main
As you already have a solution, I would present you with another one:
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int nRolls = 100, nDice = 6; // default values
Scanner in = new Scanner(System.in);
System.out.print("Number of throws: ");
nRolls = in.nextInt();
System.out.print("Number of sides on the dices: ");
nDice = in.nextInt();
int minSum = 2, maxSum = 2 * nDice;
int[] hist = new int[maxSum - minSum + 1];
Random rand = new Random();
for (int iter = 1; iter <= nRolls; iter++) {
int throw1 = 1 + rand.nextInt(nDice), throw2 = 1 + rand.nextInt(nDice);
int sum = throw1 + throw2;
hist[sum - minSum]++;
}
System.out.println("Number of rolls: " + nRolls);
System.out.println("Number of sides of the dice: " + nDice);
System.out.println("Sum of Dice Percentage");
for (int i = 0; i < hist.length; i++) {
System.out.println(String.format(" %2d %5.2f%%", i + minSum, hist[i] * 100.0 / nRolls));
// System.out.println(" " + (i+minSum) + " " + (hist[i]*100.0/nRolls);
}
in.close();
}
}
It shows you how to use arrays to solve this task. Each entry in the array holds the number of throws that came up with the corresponding sum. You always have 2*nDice - 1 possible sums (you can not reach 1 with two dices), so the size of the array is dependent on the number of sides on the dice.
Then you just iterate through all throws and add 1 to the corresponding histogram entry (note that I offset the histogram, so hist[0] corresponds to a sum of 2, hist[1] to a sum of 3, etc).
At the end, you can just calculate the percentage. (It's not a probability, it's the percentage that this sum occured in our simulation. If you make the number of rolls larger, this percentage will be an approximation of the probability.)
At the end, you just print it out. The String.format stuff is just for alignment of the values. If you are confused about it, just use
System.out.println(" " + (i+minSum) + " " + (hist[i]*100.0/nRolls);
instead.
Change numberOfRolls initiation to 1 instead of 0.
for( int numberOfRolls = 1; numberOfRolls <= rolls; numberOfRolls++) {
If numberOfRolls is 0, all your division operations results in divide by ZERO.
probability2 = diceTotal2 / numberOfRolls;

Categories