Reputation: 15
import java.util.Random;
import java.util.Scanner;
public class dieClass
{
public static void main(String []args)
{
Random gen = new Random();
Scanner reader = new Scanner(System.in);
System.out.println("How many times do you want to roll?");
int rollamt = reader.nextInt();
for (int i = 0; i < rollamt; i++)
{
int dice1 = gen.nextInt(6) + 1;
int dice2 = gen.nextInt(6) + 1;
int total = dice1 + dice2;
int [] arrayDice = new int [rollamt];
for (int r = 0; r < arrayDice.length; r++)
{
arrayDice[r] = total;
}
System.out.println("sum is " + total);
}
}
}
I was on to something but I give up. How do i keep track of how many times the sum of the two die was chosen? A while loop ? (The result of the two die can only be between 2 and 12)
So for example I want to have a loop that will Add one to its counter for its assigned number
x = sum of two die
y = number of times
The output can be "the number x was rolled y times"
Upvotes: 1
Views: 958
Reputation: 405
You can create a Map that is a Map of the number to the number of times rolled.
java.util.Map<Integer, Integer> rollMap = new java.util.HashMap<Integer, Integer>();
for (int i = 0; i < rollamt; i++)
{
int dice1 = gen.nextInt(6) + 1;
int dice2 = gen.nextInt(6) + 1;
int total = dice1 + dice2;
Integer count = rollMap.get(total);
if (null == count)
{
rollMap.put(total, Integer.valueOf(1));
}
else
{
rollMap.put(total, Integer.valueOf(count + 1));
}
}
for (Map.Entry<Integer, Integer> entry : rollMap.entrySet())
{
System.out.println("Number " + entry.getKey()+ " was rolled " + entry.getValue() + "times")
}
Upvotes: 0
Reputation: 4669
Inside of your while loop, you simply have another array that holds a count of each possible roll.
You've already got the total, right here.
int total = dice1 + dice2;
Just add an array, outside of the loop to start a count:
int possibleRolls[]=new int[13]
and inside your loop:
possibleRolls[total]++;
When the loop is finished, you can check the indexes in the array to see how many each total was rolled.
Upvotes: 1