骰子滚动游戏模拟器
问题描述:
我是新来的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 + ".");
}}
答
至于什么大卫Wallance说,这两个骰子的总和,可以由此实现。
count[rollOne+rollTwo+1]++;
用千次模拟试验了代码,没有问题。
答
由于1<=rollOne<=6
和1<=rollTwo<=6
我认为你需要count[rollOne+rollTwo-1]++;
:那么count[i]
将代表的次一共有i+1
与两个骰子被抛出数。
肯定你打算写'count [rollOne + rollTwo] ++;'对吗? – 2015-03-02 05:29:01
或'count [rollOne + rollTwo-1] ++;',no? – 2015-03-02 06:48:46
工作感谢你! – K455306 2015-03-03 05:26:36