how can i calculate probabilities in java without the use of array lists?

Some remarks about your code:

The declaration of your random variable should be done outside the loop. Whenever you use the new operator in java, you create an object. Since the loop is run several times (in your case 20000 times), you also create 20000 objects which is not useful. But if you do it before the loop, only one object is created, which you can use again and again.

For this task you do not need deeper knowledge of statistics. For the task you only need methods from the descriptive statistic and not from inferential statistic. You should calculate the impirical probability which is calculated simply by dividing favourable events / all events. For this you only need a counter to remember how often the randomly thrown numbers corresponded to the desired sum. For this purpose it would also be easier to use a for loop instead of a while loop.

You can use DecimalFormatter and display your probabilities with the desired decimal places.

I have modified your code with my remarks and suggestions and removed some unnecessary variables.

import java.text.DecimalFormat;
import java.util.Random;
import java.util.Scanner;

public class Lab7Part2 {

    public static void main(String[] args) {
        // new input
        Scanner input = new Scanner(System.in);
        // Define vars
        int dice1, dice2, total;
        long landmark = 1_000;;
        double probability = 0;
        int trials = 40_000;
        int countOfTotal = 0;
        DecimalFormat df = new DecimalFormat("#.#####");

        // Name of program
        System.out.println("Probability Testing Program");
        System.out.println();
        System.out.print("What die total do you wish to test for (2-12): "); // prompt total dice rolls
        total = input.nextInt(); // store input as "total"
        System.out.println();
        System.out.println("Computed probability for die throw = " + total);
        System.out.println();
        System.out.println("Die throws     Probability");

        Random rand = new Random();
        for (int i = 1; i <= trials; i++) {
            dice1 = 1 + rand.nextInt(6);
            dice2 = 1 + rand.nextInt(6);
            if (dice1 + dice2 == total) {
                countOfTotal++;
            }
            if (i % landmark == 0) {
                probability = (double) countOfTotal / i;
                System.out.printf("     %5d     %-6s \n", i, df.format(probability));
            }
        }
    }
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top