骰子滚动游戏模拟器

时间:2015-03-02 05:22:17

标签: java

我是Java新手并正在构建一个骰子游戏,我需要合并两个骰子而不是一个。我用的是roll = r.nextInt(12)+2;但这不会给我和滚动两个单独骰子相同的几率。我改变了下面的randoms,但现在它将输出加倍。任何帮助将不胜感激。

import java.util.*;

公共课W7KyleAbel {

public static void main(String[] args)
{
    // Utilities
    Scanner in = new Scanner (System.in);
    Random r = new Random();

    // Variables
    int numberOfrolls = 0;
    int rollOne = 0;
    int rollTwo = 0;
    int [] count = new int [12];

    //Welcome Statement
    System.out.println("Welcome to the dice throwing simulator!");

    //Get the number of rolls from the user
    System.out.println("How many dice rolls would you like to simulate?");
    numberOfrolls = in.nextInt();

    //Simulate the number of rolls
    for (int i = 0; i < numberOfrolls; i++)
    {
        rollOne = r.nextInt(6)+1;
        rollTwo = r.nextInt(6)+1;
        count[rollOne+rollTwo]++;
    } //end for

    //Iterate through the list of rolled counts & histogram
    for(int i = 1; i < count.length; i++)
    {
        StringBuffer outputBuffer = new StringBuffer(100 * count[i] / numberOfrolls);
        for (int j = 0; j < count[i]; j++)
        {
            outputBuffer.append("*");
        }//end for
        System.out.println((i+1)+ ":" + outputBuffer);
    }//end for

    //Results
    System.out.println("DICE ROLLING SIMULATION RESULTS\n" +
            "Each \"*\" represents 1% of the total number of rolls.\n" +
            "Total number of rolls = "+ numberOfrolls + ".");

} }

2 个答案:

答案 0 :(得分:0)

由于1<=rollOne<=61<=rollTwo<=6我认为您需要count[rollOne+rollTwo-1]++;:然后count[i]将代表两次投放i+1的总次数骰子。

答案 1 :(得分:-1)

正如David Wallance所说,两个骰子的总和可以通过这个来实现。

count[rollOne+rollTwo+1]++;

用一千次模拟试验代码没有问题。