Finding probability using nested for loops in Java - 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;

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

Having issues with dice probability program

I am trying to make a program that calculates dice rolls using random digits and returns the probability of each sum happening for different numbers of rolls and trials. This code however only results in probabilities of zero displaying. This seems to be an issue with the establishment of the match variable in the nested for loop. Wondering what I am doing wrong. Is it establishing the match variable based on the counter?
import java.util.Random;
import java.util.Scanner;
public class DiceProbability
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
Random randNumList = new Random();
System.out.println("How many sides do the dice have: ");
int diceSides = in.nextInt();
System.out.println("How many times will the dice be rolled: ");
int diceRolls = in.nextInt();
int highestSum = diceSides * 2;
int diceRoll1 = 0;
int diceRoll2 = 0;
int match = 0;
int totalOfDiceRolls = 0;
int counter = 0;
int counter2 = 0;
System.out.println("Rolls total " + "Probability");
for(counter=2;counter<=highestSum;counter ++)
{
for(counter2=1;counter2<=diceRolls;counter2 ++)
{
diceRoll1 = (randNumList.nextInt(11)+1);
diceRoll2 = (randNumList.nextInt(11)+1);
int totalOfRolls = diceRoll1 + diceRoll2;
if(totalOfDiceRolls != counter)
{
match = match + 0;
}
else
{
match ++;
}
}
System.out.println(match);
double probabilityOfSum = (match * 100 / diceRolls);
System.out.println(counter + ": " + probabilityOfSum);
counter2 = 1;
}
}
}
If I understand this correctly you are trying to calculate the relative frequency for each sum of two dices being rolled. If it's the case please edit your question as it's not that explicit in what your asking, especially that you have always two dices.
If you have two sided dices, your mathematical probability is as per below :
P(of having 2) = 1/4
P(of having 3) = 2/4
P(of having 4) = 1/4
All others are equal to 0.
Here is the code to achieve this. You need to save the frequency in an array and output correctly in dividing by the number of experiment.
Note: if you run this for a number less than 1000 this won't be accurate mathematically so it doesn't really make sense the user input the number of experiments in this case... ( in my opinion)
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("How many sides do one dice have: ");
int diceSides = in.nextInt();
int[] results = new int[diceSides * 2 + 1];
Random rnd = new Random();
for (int i = 0; i < 10000; i++) {
int resultdice1 = rnd.nextInt(diceSides) + 1;
int resultdice2 = rnd.nextInt(diceSides) + 1;
int sum = resultdice1 + resultdice2;
results[sum] = results[sum] + 1;
}
for (int i = 0; i < results.length; i++) {
System.out.println("Probability to have sum of " + i + " is : " + (double) results[i] / 10000);
}
}
Output :

Java-Number of scores needs to be one less in answer

So here is my code:
package e7;
import java.util.Scanner;
public class Q1 {
public static void main(String[] args)
{
double[] scores = new double[10];
double sum = 0.0D;
int count = 0;
Scanner sc = new Scanner(System.in);
do {
System.out.print("Enter a new score (-1 to end): ");
scores[count] = sc.nextDouble();
if (scores[count] >= 0.0D)
sum += scores[count];
}
while (scores[(count++)] >= 0.0D);
System.out.println("The total number of scores is: " + count );
double average = sum / (count - 1);
int numOfAbove = 0;
int numOfBelow = 0;
for (int i = 0; i < count - 1; i++) {
if (scores[i] >= average)
numOfAbove++;
else
numOfBelow++;
}
System.out.printf("Average is " + "%.2f\n",average);
System.out.println("Number of scores above or equal to the average " + numOfAbove);
System.out.println("Number of scores below the average " + numOfBelow);
}
}
How do make it display the correct number of scores calculated? If I input 2 numbers and then do the -1 one to end it keeps saying 3 scores. Should only be two. How do I fix this? Thanks
System.out.println("The total number of scores is: " + count );
You probably want:
System.out.println("The total number of scores is: " + (count - 1));
You could also change your loop from a do while to a while loop as follows,
while (true) {
System.out.print("Enter a new score (-1 to end): ");
double tempDouble = sc.nextDouble();
if (tempDouble >= 0.0D)
scores[count] = tempDouble;
sum += scores[count];
count++;
else
break;
}
That way as if your double input isn't correct it would break out of the while loop when the user entered -1. You might have to tweak it a bit for your use case.

control structure, repetition exercise: How to get the sum of the digits of a number?

Guys can you please help me answer this exercise using for loop without using string methods.
Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. For example, the program should output the individual digits of 3456 as 3 4 5 6 and the sum as 18,and output the individual digits of -2345 as 2 3 4 5 and the sum as 14.
This is the code:
package MyPackage;
import java.util.*;
public class Integer
{
public static void main(String args[])
{
Scanner console = new Scanner (System.in);
int input;
int sum = 0;
int num1 = 0;
int counter = 1;
String num = "";
System.out.print("enter a number: ");
input = console.nextInt();
if (input == (-input))
{
input = input * (-1);
num = String.valueOf(input);
num1 = num.length();
System.out.print("the digits of " + input + " are: ");
for (int i = 0; i < num1; i++ )
{
String var = num.substring(i,counter);
int var1 = Character.getNumericValue(var.charAt(0));
System.out.print(var + " ");
sum = sum + var1;
counter++;
}
System.out.println();
System.out.println("the sum is: " + sum);
}
else
{
num = String.valueOf(input);
num1 = num.length();
System.out.print("the digits of " + input + " are: ");
for (int i = 0; i < num1; i++ )
{
String var = num.substring(i,counter);
int var1 = Character.getNumericValue(var.charAt(0));
System.out.print(var + " ");
sum = sum + var1;
counter++;
}
System.err.println();
System.out.println("the sum is: " + sum);
}
}
}
Iterating all the digits from right to left is easy enough - you just keep dividing by 10 and keeping the remainder.
Since you need to print them from left to right, but there don't seem to be any constraint on the memory usage, you could just keep them in a list, and print it backwards:
int num = ...; // inputed from user
List<Integer> digits = new LinkedList<>();
int sum = 0;
// Extract the digits and the sum
while (num != 0) {
int digit = num % 10;
digits.add (digit);
sum += digit;
num /= 10;
}
// Print backwards:
System.out.print ("The digits are: ");
for (int i = digits.size() - 1; i >= 0; --i) {
System.out.print (digits.get(i) + " ");
}
System.out.println();
System.out.println("Their sum is: " + sum);

Passing array through average method, resulting in low percent

For some reason the average is being populated wrong when I pass the array to the method I get a really low percent. It almost seems like since the Array shotsMade is only recording integers for made shots and not misses it is not calculating off the right base.
import java.util.*;
public class Test {
public static void main(String[] args) {
int myGameCounter = 1;
int shotCount = 0;
int shotCount1 = 0;
int [] shotsMade = new int [5];
int sum = 0;
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
//Game #1
System.out.println("Game " + myGameCounter + ":");
Random r = new Random();
myGameCounter++;
shotCount = 0;
for (int i = 0; i < 10; ++i){
boolean in = tryFreeThrow(percent);
if (in) {
shotCount++;
System.out.print("In" + " ");
}
else {
System.out.print("Out" + " ");
}
}
System.out.println("");
System.out.println("Free throws made: " + shotCount + " out of 10");
shotsMade[0]= shotCount;
//Game #2
System.out.println("");
System.out.println("Game" + myGameCounter + ":");
myGameCounter++;
shotCount1 = 0;
for (int i = 0; i < 10; ++i){
boolean in = tryFreeThrow(percent);
if (in) {
shotCount1++;
System.out.print("In" + " ");
}
else {
System.out.print("Out" + " ");
}
}
System.out.println("");
System.out.println("Free throws made: " + shotCount1 + " out of 10");
shotsMade[1]= shotCount1;
System.out.println("");
System.out.println("Summary:");
System.out.println("Best game: " + max(shotsMade));
System.out.println("Total Free Throws Made: " + sum(shotsMade) + " " + "out of 20");
System.out.println("Average Free Throw Percentage: " + average(shotsMade) +"%");
}//main
public static boolean tryFreeThrow(int percent) {
Random r = new Random();
int number = r.nextInt(100);
if (number > percent){
return false;
}
return true;
}
public static float average(int nums[]) {
int total = 0;
for (int i=0; i<nums.length; i++) {
total = total + nums[i];
}
float f = (total / nums.length);
return (float)total /(float)nums.length;
}
public static int sum(int nums[]) {
int sum = 0;
for (int i=0; i<nums.length; ++i) {
sum += nums[i];
}
return (int)sum;
}
public static int max(int nums[]) {
int max=nums[0];
for (int i=1; i<nums.length; i++) {
if (nums[i] > max)
max = nums[i];
}
return max;
}
}//class
You are calculating the avarage of 5 numbers but you only set 2. So if all shots hit your array will look like this: 10, 10, 0, 0, 0 and the avarage will be 4.
Old issue, you are using integer arithmetic total / nums.length with returns you an int value. You later assign it to a float, but the value already has been truncated.
Just change one of the values to float before the division, v.g. ((float) total) / num
Among others, your expression
float f = (total / nums.length);
will yield an inaccurate result.
Both total and nums.length are integers, and any operation between integers always results in an integer.
Example: if total=10 and nums.length=3, you'd expect the result to be 3.333... but actually the result is just 3. Only after that do you cast it to a float, resulting in 3.0.
To get the required result, you need to cast both integers to floats before dividing:
float f = (float) total / (float) nums.length;

Categories