Closed. This question does not meet Stack Overflow guidelines。它当前不接受答案。












想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。

3年前关闭。





这是我第一次基于我自己的方式为Java编写代码,因此我希望您是否愿意对这个代码进行审查并提供反馈或建设性的批评。

目标是掷出2个骰子,并掷1万次。添加对并显示其频率。

代码运行良好,但也许我正在寻找一些逻辑错误或更好的方法来执行此操作

/**
 * 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等于ice时迭代就停止,然后在确保与diceValue [dice1]或diceValue [dice2]相同的diceValue [i]上加1。
可以直接通过diceValue[dice1]++进行(同样,在知道dice1 == dice2之后

09-27 00:25