骰子模拟和使用数组的值

时间:2016-06-22 06:14:59

标签: java arrays

这是我第一次根据自己的需要为Java编写代码,所以我希望你有人能够对这段代码进行审核并提供反馈或建设性的批评。

目标是掷2个骰子和10k次。添加对并显示其频率。

代码运行正常,但我可能会看到一些逻辑错误或更好的方法来执行此操作

/**
 * Use the Random Number generator to write a java application that simulates a pair of dice.
 * Throwing the pair of dice 10,000 times- Add the values for the pair
 * Print the frequency at the end of 10,000 runs
 * @author 
 *
 */

import java.util.Random;

public class diceSimulation {

    public static void main(String[] args) {
        /**
         * Declare variables and store dice max roll in Thousand
         */
        final int THOUSAND = 10000;
        int counter, dice1, dice2;

        //initiate an array with elements to keep count
        int [] diceValue = new int [7];

        // display welcome message. no other purpose but trial
        welcome ();

        // create new instance of random 
        Random rollDice = new Random();

        /**
         * Set counter to start from 1 and go till desired constant number
         * Rolling two separate dices and storing values in dice1 & dice 2 respectively
         */
        for (counter=1; counter<=THOUSAND;counter++){

            dice1=rollDice.nextInt(6) +  1;
            dice2=rollDice.nextInt(6) + 1;

            // If statement to check if values are the same or not
            if (dice1==dice2){
                // IF values are same then go into for loop and store value in array element
                for (int i=1; i<=6; i++){
                    if (dice1 == i && dice2 == i){
                        // add value for the number displayed into the array
                        diceValue [i] += 1;
                    }
                }
            }

        }
        // Display results totals of paired rolls 
        for (int a=1; a<diceValue.length; a++){
            System.out.println(" You rolled set of " + a + " " + diceValue[a] + " times");
        }

    }

    public static void welcome () {
        System.out.println("welcome to dice world!");
    }

}

1 个答案:

答案 0 :(得分:1)

// If statement to check if values are the same or not
        if (dice1==dice2){
            // IF values are same then go into for loop and store value in array element
            for (int i=1; i<=6; i++){
                if (dice1 == i && dice2 == i){
                    // add value for the number displayed into the array
                    diceValue [i] += 1;
                }
            }
        }

这整个部分有点多余。

之后你就知道dice1 == dice2你只迭过i来停止当它等于两者然后你加1到diceValue [i],它确保与diceValue [dice1]或diceValue [dice2]相同]。 这可以由diceValue[dice1]++直接进行(再次,在知道dice1 == dice2

之后)