2015-03-02 183 views
0

我是新来的Java和建立一个骰子游戏,我需要合并两个骰子,而不是一个。我正在使用roll = r.nextInt(12)+2;但那不会像滚动两个单独的骰子一样产生同样的可能性。我改变了以下的随机数,但现在它将输出翻倍。任何帮助将不胜感激。骰子滚动游戏模拟器

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

肯定你打算写'count [rollOne + rollTwo] ++;'对吗? – 2015-03-02 05:29:01

+0

或'count [rollOne + rollTwo-1] ++;',no? – 2015-03-02 06:48:46

+0

工作感谢你! – K455306 2015-03-03 05:26:36

回答

-1

至于什么大卫Wallance说,这两个骰子的总和,可以由此实现。

count[rollOne+rollTwo+1]++; 

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

+1

甚至没有'ArrayIndexOutOfBoundsException'?我原以为你会得到至少一个11或12在一千卷...... – 2015-03-02 06:52:20

+0

@James_D不,我用他的代码刚刚取代2提到的一个计数,结果是正常的。 – Weiest 2015-03-02 07:55:08

+0

@James_D当我输入的金额高于10时,我收到一个ArrayIndexOutOfBoundsException。例如100或1000.您是否知道为什么它可以用于较低的金额? – K455306 2015-03-04 00:52:09

0

由于1<=rollOne<=61<=rollTwo<=6我认为你需要count[rollOne+rollTwo-1]++;:那么count[i]将代表的次一共有i+1与两个骰子被抛出数。