java - 骰子模拟并使用数组作为值

标签 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!");
    }

}

最佳答案

// 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

关于java - 骰子模拟并使用数组作为值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37959944/

相关文章:

java - 多线程将如何影响 Easy Rules 引擎?

javascript - AngularJS:为什么我的 ng-options 没有出现?

python - numpy 数组的累积 argmax

arrays - Ruby:查找数组中下一个匹配项的索引,或查找偏移量

java - 领事健康检查员

java替换德语变音符号

java - java中未压缩文件的大小

java - 从渲染器接收消息超时

c - 在链表中存储节点数组

c - 测试 2 次刺痛是否有相同的单词 (C)