掷骰子的次数

时间:2018-03-22 02:58:04

标签: java arrays for-loop

程序滚动一定数量的骰子一定次数,所有这些都是由用户设定的。我一直在调试和排除故障为什么它现在不工作4天而且无法解决。

我知道它的一个问题是生成随机数一定次数(每次在第38行抛出的模具),但是当代码编译方式低于所有数组时,增加的数组是要使用的骰子数量(由用户输入),我无法想出一种方法,使程序循环随机数生成器,同时仍然增加数组值,抛出骰子的所有数量。

 package DiceRolls_2;

import java.util.Scanner; 
import java.lang.Math; 

public class DiceRolls_2
{
public static void main(String[] args) 
{
Scanner input = new Scanner(System.in); 
int numRolls;   //number of rolls
int outcome;    //index value to be +1'd
int numDice;    //number of dice to be thrown
int numSides;   //number of sides per die
int arraySize;  //size of array (dependant on number of sides)
int minRoll;    //minimum roll value (number of die (each one rolls 1)
int maxRoll;    //maximum roll value (number of sides (each side increments +1 to total roll possibility))

/* prompt user for number of rolls */ 
System.out.print("How many rolls? "); 
numRolls = input.nextInt(); //sets number of rolls

System.out.print("How many dice to roll? ");
numDice = input.nextInt();

System.out.print("How many sides per die? ");
numSides = input.nextInt(); 

maxRoll = numSides*numDice; //max roll is equal to num sides because the highest value number is the latest (highest) side number
minRoll = numDice;          //minimum roll is equal to number of dice since each dice has a 1 value
arraySize = maxRoll + 1;    //size of array depends on the maximum roll value + 1 for positioning of index values
int[] outcomes = new int[arraySize]; 


/* roll dice and add to outcomes */ 
for (int roll = 0; roll <= numRolls; roll++) 
{
    int numberRolled = (int) (numSides * Math.random() + 1);
    outcome = numberRolled;
    outcomes[outcome] += 1; 
}



/* show counts of outcomes */ 
for (int i = minRoll; i <= maxRoll; i++)            //3 is the minimum number (1) all number of dice can roll (dependant on number of dice are being rolled)
{                                                   //18 is maximum number all 3 dice (6 per die) can roll (dependant on number of dice are being rolled) 
    System.out.println(i + ": " + outcomes[i]);     //prints all array values with number of occurances
}
input.close();
    }
}

1 个答案:

答案 0 :(得分:1)

结果的数量是骰子的数量乘以角色的数量(而不是边数)。我简化了你的代码,你只需要一个循环来存储和打印(例如),你的变量声明可以移动到需要它们的地方。像,

Scanner input = new Scanner(System.in);
System.out.print("How many rolls? ");
int numRolls = input.nextInt();

System.out.print("How many dice to roll? ");
int numDice = input.nextInt();

System.out.print("How many sides per die? ");
int numSides = input.nextInt();
int[] outcomes = new int[numDice * numRolls];

for (int roll = 0; roll < outcomes.length; roll++) {
    outcomes[roll] = 1 + (int) (numSides * Math.random());
    System.out.printf("%d: %d%n", roll, outcomes[roll]);
}