Sorry But This is going to be a long post.

For AP Computer Science Online we had a very noneducational lesson on nested loops, then we had a very difficult program to write afterwards here it is:

Write a program to simulate tossing a pair of 11-sided dice and determine the percentage of times each possible combination of the dice is rolled.

3. Ask the user to input how many times the dice will be rolled.

4. Calculate the probability of each combination of dice. (You may want to start with

more familiar six-sided dice.)

5. Print the results neatly in two columns (do not worry about excessive decimal places).

6. What is the effect on the percentages when the number of rolls is increased?

7. After the program works, you might want to make it more interesting and ask the user

to enter the number of sides on a die (singular for dice).

We need to use nested loops not a long if, else if, else statement. Here is my source code so far. It is complete and formatted correctly but the problem is that my probability comes up as 0.0. I believe it has to do with the totalMatches variable. Can someone please help me?

Code:import java.util.Scanner; import java.util.Random; public class DiceProbability { /* * @author * @version */ public static void main(String[] args) { Random rand; rand = new Random(); Scanner input; input = new Scanner(System.in); int die1, die2; int sides; int diceRolls; int sum; int totalRolls; int sumOfBothDice; int totalMatches = 0; System.out.println("Welcome to the Dice Probability Game!"); System.out.print("Please enter the amount of sides you want on the dice: "); sides = input.nextInt(); if(sides < 1) { System.out.println("You cannot have 0 or negative sides on dice."); return; } System.out.print("Please enter the amount of times you want to roll the dice: "); diceRolls = input.nextInt(); if(diceRolls < 1) { System.out.println("You cannot roll a dice 0 or negative times and find its probability."); return; } System.out.println(); System.out.println("Sum of the Dice \t\t\t\t Probability"); System.out.println("-------------------------------------------------------------"); for(sum = 2; sum <= 2*sides; sum ++) { for(totalRolls = 0; totalRolls <= diceRolls; totalRolls ++) { die1 = rand.nextInt(sides) + 1; die2 = rand.nextInt(sides) + 1; sumOfBothDice = die1 + die2; if(sumOfBothDice == sum) { totalMatches += 1; } } double probability = (double)(totalMatches / totalRolls) * 100; System.out.println(sum + " :s \t\t\t\t\t " + probability); totalMatches = 0; } } }

Tweet This+ 1 thisPost To Linkedin