I am working on this question and I can not figure out how to get an array to keep track of the rolls in main and how to loop call the method that is doing the rolls. (Please help I am working on this by myself no teacher.)
The Problem:
Write a program that simulates rolling two dice. Prompt the user to enter the number of dice rolls. Use a loop to repeatedly call a method that simulates a dice roll and returns the total of the two dice to main. Keep track of the rolls in an array in main, and end the program by showing the results of the rolls.
Sample Output:
How many times should I roll the dice? 100
Results for 100 dice rolls
2 was rolled 4 times
3 was rolled 2 times
4 was rolled 1 times
5 was rolled 8 times
6 was rolled 15 times
7 was rolled 16 times
8 was rolled 17 times
9 was rolled 18 times
10 was rolled 10 times
11 was rolled 6 times
12 was rolled 3 times
My code so far:
import java.util.Scanner;
public class TestingCenter {
private static Scanner input;
public static void main(String[] args){
System.out.println("How many times should I roll the dice? ");
int answer = input.nextInt();
for (int x = 0; x < answer; x++) {
}
}
public static int amount(int x){
int die1;
int die2;
int roll;
die1 = (int)(Math.random()*6) + 1;
die2 = (int)(Math.random()*6) + 1;
roll = die1 + die2;
return roll;
}
}
This is implementation with int[] in main method :
import java.util.Random;
import java.util.Scanner;
public class TestingCenter {
private static final Random random = new Random();
public static void main(final String[] args) {
System.out.println("How many times should I roll the dice? ");
int answer = 0;
try (Scanner scanner = new Scanner(System.in)) {
answer = scanner.nextInt();
}
final int[] results = new int[11];
for (int x = 0; x < answer; x++) {
results[amount() - 2]++;
}
System.out.println(String.format("Results for %s dice rolls ", answer));
for (int i = 0; i < 11; i++) {
System.out.println(String.format("%s was rolled %s times", i + 2, results[i]));
}
}
public static int amount() {
return random.nextInt(6) + random.nextInt(6) + 2;
}
}
Tested output:
How many times should I roll the dice?
100
Results for 100 dice rolls
2 was rolled 1 times
3 was rolled 8 times
4 was rolled 10 times
5 was rolled 12 times
6 was rolled 14 times
7 was rolled 18 times
8 was rolled 13 times
9 was rolled 12 times
10 was rolled 6 times
11 was rolled 4 times
12 was rolled 2 times
You may try something like this (Explanation in Comments):
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class TestingCenter {
// map to hold the results
static Map<Integer, Integer> result = new HashMap<>();
public static void main(String[] args){
// fill the map with numbers from 1 to 12 like the die
// each number has a corresponding value, initially 0
for(int i=1; i<=12; i++){
result.put(i, 0);
}
// initialize the Scanner
Scanner input = new Scanner(System.in);
System.out.print("How many times should I roll the dice? ");
int answer = input.nextInt();
// repeat the rolling
for (int x = 0; x < answer; x++) {
rollDice();
}
input.close();
// final result
System.out.println("Results for " + answer + " dice rolls:");
for(Integer die : result.keySet()){
System.out.println(die + " was rolled " + result.get(die) + " times");
}
}
// this method returns the roll result
public static void rollDice(){
int die1, die2, roll;
die1 = (int)(Math.random()*6) + 1;
die2 = (int)(Math.random()*6) + 1;
roll = die1 + die2;
// increment the current value and update the map result
result.put(roll, result.get(roll)+1);
}
}
Test
How many times should I roll the dice? 100
Results for 100 dice rolls:
1 was rolled 0 times
2 was rolled 5 times
3 was rolled 1 times
4 was rolled 8 times
5 was rolled 17 times
6 was rolled 12 times
7 was rolled 22 times
8 was rolled 8 times
9 was rolled 10 times
10 was rolled 7 times
11 was rolled 9 times
12 was rolled 1 times
import java.util.Arraylist and simply add each value to the List as your looping answer number of times.
public static void main(String[] args)
{
input = new Scanner(System.in);
System.out.println("How many times should I roll the dice? ");
int answer = input.nextInt();
List<Integer> list = new ArrayList<Integer>();
for (int x = 0; x < answer; x++)
{
list.add(amount(x));
}
}
What you could do is create a HashMap, with a key containing the result of the roll, and the second value being the number of times this result was rolled out. It would give something like this :
HashMap<Integer, Integer> results = new HashMap<Integer, Integer>();
for (int x = 0; x < answer; x++) {
int roll = amount(x);
if(results.get(roll) == null) {
results.put(roll, 1);
} else {
results.put(roll, results.get(roll) +1);
}
}
Then, when printing, you just have to do a for loop (from 1 to 12) and then get the value associated to every number looped.
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
package HomePlace;
import java.util.Scanner;
import java.util.Random;
public class DiceRolls {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many sides? ");
int Usides = input.nextInt();
System.out.print("How many dice to roll? ");
int Udices = input.nextInt();
System.out.print("How many rolls? ");
int Urolls = input.nextInt();
int[] outcomes = new int[Usides * Udices];
for (int rolls = 0; rolls < Urolls; rolls++) {
outcomes[sum(Usides, Udices)] += 1;
}
for (int i = Udices; i <= Urolls; i++) {
System.out.println(i + ": " + outcomes[i-1]);
}
}
public static int sum(int Us, int Ud) {
int dicesum = 0;
for (int i = 0; i <= Ud; i++) {
int dots = (int) (Math.random() * Us + 1);
dicesum += dots;
}
return dicesum;
}
}
This is a code where the User declares how many sides (of the dice), how many dice (number of dice), and how many rolls that the User would perform.
For example, if the User choose the dice would have 3 sides, the variable would be 1~3
and If the User inputs 5 dices and 5 rolls, it would be throwing 5 (3sided) dice for 5 times.
My output should display the possible sums and how many times that sum came out. For example, If I throw 2 of 6 sided dice 2 times, the output should count the number of sums that came out from each roll.
Now my problem is I get the error
How many sides? 3
How many dice to roll? 4
How many rolls? 5
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 12 out of bounds for length 12
at HomePlace.DiceRolls.main(DiceRolls.java:21)
and if I put large input
How many sides? 123
How many dice to roll? 123
How many rolls? 123
123: 0
I only get this output. where I want the output would be
How many sides on the die? 7
How many dice to roll? 5
How many rolls? 100
5: 0
6: 0
7: 0
8: 0
9: 1
10: 1
11: 2
12: 0
13: 2
14: 5
15: 9
16: 5
17: 4
18: 2
19: 9
20: 6
21: 8
22: 11
23: 10
24: 7
25: 6
26: 5
27: 2
28: 1
29: 3
30: 1
31: 0
32: 0
33: 0
34: 0
35: 0
Obviously I did something wrong in that code.. can i get help?
Using the first sample from your question as an example, i.e. four dice where each dice has three sides and you roll all four dice a total of five times.
The minimum outcome will be 4 when each dice lands on 1 (one), i.e. the minimum outcome equals the total number of dice.
The maximum outcome will be 12 when each dice lands on 3 (three), i.e. the maximum outcome is the number of dice multiplied by the number of sides on each dice.
Array outcomes stores the frequency of each outcome. So the size of the array needs to be the number of possible outcomes. Using the above example, the size needs to be nine, i.e. 12 - 4 + 1 or in other words the maximum outcome minus the minimum outcome plus one.
The first for loop in method main() performs the dice rolls and adjusts the values in array outcomes. You need to adjust the actual outcome to the array index. Again using the above example, if the outcome is the minimum, i.e. 4, then that corresponds to the first element in outcomes, so you need to change 4 to 0 (zero). Similarly, when the outcome is 5, you want to update the second element in outcomes, so you need to change 5 to 1 (one). As you can see, in both cases you need to subtract the minimum outcome from the actual outcome you got in order to get the real index of the element in outcomes that needs to be incremented.
The for loop in method sum() needs to repeat according to the number of dice. So for four dice, the loop needs to repeat four times. So you can write the loop as:
for (int i = 1; i <= Ud; i++) {
Finally you print the results. You want to display every element in outcomes but when you display the element value, you need to add the minimum outcome to the element index because, as I wrote above, element 0 (zero) in array outcomes really means the minimum outcome.
Here is the code. I added more print() methods so you can see what the code is doing.
import java.util.Scanner;
public class DiceRolls {
public static int sum(int Us, int Ud) {
int dicesum = 0;
for (int i = 1; i <= Ud; i++) {
int dots = (int) (Math.random() * Us + 1);
System.out.printf("dice %d landed on %d%n", i, dots);
dicesum += dots;
}
return dicesum;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many sides? ");
int Usides = input.nextInt();
System.out.print("How many dice to roll? ");
int Udices = input.nextInt();
System.out.print("How many rolls? ");
int Urolls = input.nextInt();
int maximumOutcome = Udices * Usides;
int[] outcomes = new int[maximumOutcome - Udices + 1];
System.out.printf("Outcomes for %d rolls of %d, %d-sided dice.%n", Urolls, Udices, Usides);
for (int rolls = 1; rolls <= Urolls; rolls++) {
System.out.printf("%nRoll %d:%n", rolls);
int sum = sum(Usides, Udices);
System.out.printf("Total: %d%n", sum);
outcomes[sum - Udices]++;
}
System.out.println("====================================================================");
System.out.println("Outcomes: ");
for (int i = 0; i < outcomes.length; i++) {
System.out.println((i + Udices) + ": " + outcomes[i]);
}
}
}
So I am very new to the Java language and I'm attempting to put together a dice roller of sorts for character stat generation for D&D (Dungeons and Dragons).
What I want the program to do is roll x number of D6, x amount of times. X is to be input by the user. I also need the program to ask if it is to re-roll a result of 1 on a D6 roll. Plus, the program must only keep the highest 3 numbers of the rolled dice. It then needs to output the results of each grouping of dice rolls, instead of totaling them all together.
So an example would be: I want 4 D6 rolled 6 times, and re-roll 1's.
The program output would be something along the lines of:
Your results are:
10
12
13
15
17
11.
I'm trying to write this with 3 classes, though I know it doesn't need to have 3 classes to operate. The additional classes are more of a requirement from a project standpoint.
I've managed to code what is necessary to roll a single dice, but as I said I'm very new and have almost zero idea on where to go with this.
The code I have so far is:
//Scanner is implemented in preparation for user input as more coding is
//added
import java.util.Scanner;
public class RollDie {
public static void main(String[] args) {
int SIDES = 6; // how many sides on the die?
// roll should be 1 through SIDES
int roll = (int) (Math.random() * SIDES) + 1;
// print result
System.out.println(roll);
}
}
A one-class solution with freindly user input could look like this:
private final static int SIDES = 6;
public static void main(String[] args) {
java.util.Scanner scanner = new java.util.Scanner (System.in);
System.out.println("Number of dice?");
final int dice = scanner.nextInt();
System.out.println("Number of rolls?");
final int rolls = scanner.nextInt();
System.out.println("Reroll result 1? Enter y for yes");
final boolean reroll = scanner.next().equals("y");
for (int r = 0; r < rolls; r++) {
int allDice = 0;
for (int d = 0; d < dice; d++) {
int roll = (int) (Math.random() * SIDES) + 1;
while (reroll && roll == 1) {
roll = (int) (Math.random() * SIDES) + 1;
}
allDice += roll;
}
System.out.println(allDice);
}
}
Basically, two dice are rolled randomly a bunch of times and then the two dice values are added together (You roll a 6 and a 3, your total is 9).
The frequency of how many times the total is rolled is stored in totalTally[].
So say you roll 10 times, 3 of those times you roll a total of 9, totalTally[9] = 3.
Here's my code:
import java.util.Random;
public class dice
{
public static void main(String a[])
{
System.out.println("Creating arrays to store information. This might take a while.");
int[][] tally = new int[6][6]; //Creates an array called tally to keep track of how many times each number was rolled. [Dice1][Dice2]
int[] totalTally = new int[12]; //Creates an array called totalTally to keep track of frequency of totals rolled.
int[][] roll = new int[36000000][2]; //Creates an array to store dice roll info.
System.out.println("Rolling two 6-sided dice " + roll.length + " times...");
Random r = new Random(); //Creates a new random number generator
for (int i = 0; i < roll.length; i++) //For loop that rolls the dice to fill the length of the array.
{
roll[i][0] = (r.nextInt(6) + 1); //Assigns random number between 1 and 6 to the array for dice 1 result.
roll[i][1] = (r.nextInt(6) + 1); //Assigns random number between 1 and 6 to the array for dice 2 result.
tally[roll[i][0]-1][roll[i][1]-1]++; //Increments by 1 the respective result in the tally array.
totalTally[roll[i][0] + roll[i][1]-2]++; //Increments by 1 the respective result in the totalTally array.
}
System.out.println("All done. Results are below.");
//Following lines print first table header
System.out.println("\n ROLL SUMMARY:");
System.out.println("Dice 1 + Dice 2 Frequency");
System.out.println("---------------------------------");
for (int i = 1; i <= totalTally.length; i++)//for loop goes through totalTally values
{
System.out.println(" " + i + " " + totalTally[i-1]);
}
//Following lines print second table header
System.out.println("\n DETAILED VIEW:");
System.out.println("Dice 1 Dice 2 Total Frequency");
System.out.println("---------------------------------------------");
for (int j = 1; j <= 6; j++) //For loop goes through dice 1 values
{
for (int k = 1; k <= 6; k++) // Nested for loop goes through dice 2 values
{
System.out.println(j + " " + k + " " + (j+k) + " " + tally[j-1][k-1]); //Prints line for table with dice values
}
}
}
}
and here is the output I am getting for the first table with that code:
Dice 1 + Dice 2 Frequency
1 998639
2 1997209
3 2998118
4 4000336
5 4999210
6 6001277
7 5001144
8 4000794
9 3002596
10 2001501
11 999176
12 0
Here's my issue: It's not possible to roll a 1 if you are rolling two dice.
And it IS possible to roll a 12.
So all my values need to be shifted.
What am I doing wrong?
totalTally[roll[i][0] + roll[i][1]-2]++
Why you subtract 2 ?
you should subtract 1 instead
totalTally[roll[i][0] + roll[i][1]-1]++
This is how you "tally" a single die.
Random r = new Random();
int[] die1 = new int[5]; //Creates an array to tally die 1
for (int roll = 0; roll < totalRolls; roll++) {
die1[r.nextInt(6)] += 1; // increment the index of the random roll
}
Do that for each die.
Your total tally would look like this to count individual rolls
for (int side = 1; side <= 6; side++) {
System.out.printf("%d\t%d\n", side, die1[side-1] + die2[side-1]);
}
If you want to tally the total of the rolls, sure, start printing at 2, not 1
System.out.println("Dice 1 + Dice 2 Frequency");
System.out.println("---------------------------------");
/// See here
for (int i = 1; i <= totalTally.length; i++)//for loop goes through totalTally values
{
System.out.println(" " + i + " " + totalTally[i-1]);
}
I'm trying to create a java program for my class that throws 3 dice. The player rolls the dice and earns a profit in dollars based on the three values obtained. In particular, the profit is equal to the number of even values multiplied by the sum of those values, plus the number of odd values multiplied by the sum of those values.
For example, if the player rolls 4, 5, and 2 we calculate:
2 x 6 (two even values summing to 6)
And
1 x 5 (one odd value summing to 5).
So the profit is 12 + 5 = $17.
Here is what I have so far -
import java.util.Scanner;
public class Maiorca_Hw2
{
public static void main (String [] args)
{
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter Values of Dice 1");
d1 = keyboard.nextDouble();
System.out.println("Enter Values of Dice 2");
d2 = keyboard.nextDouble();
System.out.println("Enter Values of Dice 3");
d3 = keyboard.nextDouble();
double numbers = 1,2,3,4,5,6;
double profit, dice, d1, d2, d3, oddsum, evensum;
if (d1 == 1 || d1 == 3 || d1 == 5)
oddsum =
I personally think that the program should be done in a different way and you should also use clases.
I hope this little code helps you!
First of all we must create a class called Dice, where we will set the behaviour of a dice and the interactions allowed.
You say that the player rolls, so there must be a random event, I think.
//CODE:
import java.util.Random;
public class Dice {
private final int SIDES;
//Constructor for a dice
public Dice(int sides){
//Establishes the number of sides of the dice we're using.
SIDES = sides;
}
//Methods:
public int roll(){
Random rnd = new Random();
return rnd.nextInt(SIDES) + 1;
}
}
After that, in the main class, we put it to the test.
The why of everything is in the comments
//CODE:
public class MainClass {
public static void main(String[] args) {
int moneyEarned = 0;
//We generate 3 dices with 6 sides each.
Dice d1 = new Dice(6);
Dice d2 = new Dice(6);
Dice d3 = new Dice(6);
// Then we start the simulation:
int res1, res2, res3;
res1 = d1.roll();
res2 = d2.roll();
res3 = d3.roll();
//Show results:
System.out.println("Roll results: dice 1 = " + res1 +
"; dice 2 = " + res2 + "; dice 3 = " + res3);
//We obtain the money the player must earn:
//An even number modulo 2 can only be either 1 or 0 so the same number + 1 will
//switch from 0 to 1 and the opposite thing.
//With this number we can choose which numbers we want to sum:
int oddNumbersPoints = ((res1 * (res1%2))+(res2 * (res2 % 2))+( res3 * (res3 % 2)));
int evenNumbersPoints = ((res1 * ((res1 + 1) %2)) + (res2 * ((res2+1) % 2))+( res3 * ((res3+1) % 2)));
moneyEarned = (evenNumbersPoints * 2) + oddNumbersPoints;
//Finally display the final result:
System.out.println("Even Numbers Points: " + evenNumbersPoints);
System.out.println("Odd Numbers Points: " + oddNumbersPoints);
System.out.println("Congratulations, you just earned: " + moneyEarned + "$");
}
}
/////
Finally you can change the main class to change the number of dices, the scores, so on...
(Add '}' and the main class head)
What you can do declaring primitive types, in this case double, is:
double profit = 0, dice = 2, d2 = 3;
To declare an array of doubles:
double[] numbers = {1,2,3,4,5,6};
I'm having some troubles getting this code to look neat since there are som many IF & OR statement that needs to be evaulated.
Idea: You throw five dices and pick out e.g. three of the same type 1,1,1 and throw dice the other two again and go gather points.
The tricky thing is to compare dice1,dice2,dice3,dice4,dice5 with the set of rules in order to determine how many points the player get. What code would check all the possible combination "if dicex=1 & dicex=1 & dicex=1" give player 1000 points?
int player1points = 0;
int player2points = 0;
Scanner in = new Scanner(System.in);
Random n1 = new Random();
int dice1 = n1.nextInt(6) + 1;
int dice2 = n1.nextInt(6) + 1;
System.out.println("Dice 1 shows " +dice1);
System.out.println("Dice 2 shows " +dice2);
System.out.println("Dice 3 shows " +dice3);
System.out.println("Dice 4 shows " +dice4);
System.out.println("Dice 5 shows " +dice5);
if /* 1+1+1+1+1 = 2000 */ (dice1==1&&dice2==1&&dice3==1&&dice4==1&&dice5==1){
System.out.println("You got 2000 points! Throw again?");
int points2000 = 2000;
player1points = player1points + points2000;
System.out.print("You have ");
System.out.print(player1points);
System.out.print(" points. Do you want to throw again?");
System.out.println("Yes/No?");
s = in.nextLine();
}
else if /* 1+1+1 = 1000 */ (dice1==1&&dice2==1&&dice3==1||dice2==1&&dice3==1&&dice4==1||dice3==1&&dice4==1&&dice5==1|| dice4==1&&dice5==1&&dice1==1||dice5==1&&dice1==1&&dice2==1||dice1==1&&dice2==1&&dice4==1||d ice2==1&&dice3==1&&dice5==1||dice3==1&&dice4==1&&dice1==1||dice4==1&&dice5==1&&dice1==1||dice1==1&&dice3==1&&dice5==1){
System.out.println("You got 1000 points!");
int points1000 = 1000;
player1points = player1points + points1000;
System.out.print("You have ");
System.out.print(player1points);
System.out.print(" points. Do you want to throw again?");
System.out.println("Yes/No?");
s = in.nextLine();
}
Put the results of the rolls into an arrayList, then just count the number of times the same number shows up in that array list? If there are 3 1's, give 1000 points, else if there are 5 1's give 2000 points.
So for your code you'll have the same beginning for the most part. Add in methods to populate the array list, and to iterate though/count the results of the dice rolls and return the most common and the number of times it shows up.
int player1points = 0;
int player2points = 0;
int count = 0;
int mostCommon = 0;
int maxCount = 0;
ArrayList<Integer> diceRolls = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
Random n1 = new Random();
//rollDice method (parameter would be number of dice to roll)
//checkResults method (count number of times each number 1-6 shows up)
if(maxCount == 3){
player1points += 1000;
//re-roll 2 dice if necessary
else if(maxCount == 5){
player2points += 2000;
//re-roll dice if wanted
That's just one way you could do it. Also it's always good practice to break big blocks of code down into more reader-friendly functions, and it makes debugging easier! If you need anymore help feel free to ask!