jeudi 28 mai 2015

Percentage math not coming out correctly for random dice roll

So I have this code I'm working on and it seems to run correctly except for the printing / showing percentage results. When the percentages are summed, I see that the total does not add up to 100. I feel like it may have something to do with casting, however, I don't see where the mistake is and have stepped through the code numerous times. If anyone could help me out as well as give me any tips reguarding structuring / any other noob stuff I should know, please do so! I'm a fairly new programmer and have less than half a year doing this, so like I said any tips will be appreciated. THANKS!

import java.util.Random;
import java.util.Scanner;

public class DiceRoller {

    public static void main(String[] args) {
        calculatePercentage();
    }

    //Get roll number from user
    static int getNumOfRolls(){
        Scanner input = new Scanner(System.in);

        System.out.println("How many times would you like to roll the dice?");
        int numOfRolls = input.nextInt();
        return numOfRolls;

    }
    //use object from class random to assign var value from 1 - 6 inclusive
    static int rollDice(){

        Random rand = new Random();
        int die = (rand.nextInt(6) + 1);

        return die;
    }

    static void printPercentage(int[] dieTotal, int numOfRolls){

        double totalPer = 0;
        double percent = 0;

        for(int i = 2; i < dieTotal.length; i++){

            int curNum = dieTotal[i];

            percent = ((curNum / (double)numOfRolls) * 100);
            totalPer += percent;
            System.out.printf("%d was rolled %.2f %% of the time. \n", i, percent);
        }

        System.out.println("Total percentage shown on the screen in: " + totalPer);
    }

    //store values of dice in an array. Call printPercent method defined above.
    static void calculatePercentage(){
        int numOfRolls = getNumOfRolls();

        int die1 = 0;
        int die2 = 0;
        int[] dieTotal = new int[13];

        for(int i = 0; i < numOfRolls - 1; i++){
            die1 = rollDice();
            die2 = rollDice();
            int total = die1 + die2;

            dieTotal[total]++;

        }

        printPercentage(dieTotal, numOfRolls);
    }
}




Aucun commentaire:

Enregistrer un commentaire