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);
}
}
Related
I am having trouble getting the percentage of the frequency to print. Below is the question:
Write a program to simulate the rolling of two dice. The program should use an object of class Random once to roll the first die and again to roll the second die. The sum of the two values should then be calculated. Each die can show an integer value from 1 to 6, so the sum of the values will vary from 2 to 12, with 7 being the most frequent sum and 2 and 12 being the least frequent sums. Your application should roll the dice 36,000 times. Use a one dimensional array to keep track of the number of times each possible sum appears. Display the results in tabular format. Determine whether the totals are reasonable (e.g., here are six ways to roll a 7, so approximately one-sixth of the rolls should be 7). Sample output:
Sum Frequency Percentage
2 1027 2.85
3 2030 5.64
4 2931 8.14
5 3984 11.07
6 5035 13.99
7 5996 16.66
8 4992 13.87
9 4047 11.24
10 2961 8.23
11 1984 5.51
12 1013 2.81
This is my code so far:
import java.util.Random;
public class dice_roll {
public static void main(String [] args){
Random rand = new Random();
int dice1, dice2;
int [] frequency = new int [13];
int [] rolls = new int [13];
int sum;
double percentage;
for (int i = 0; i <= 36000; i++) {
dice1 = rand.nextInt(6)+1;
dice2 = rand.nextInt(6)+1;
frequency[dice1+dice2]++;
sum = dice1 + dice2;
}
System.out.printf("Sum\tFrequency\tPercentage\n");
for (int i = 2; i < frequency.length; i++) {
percentage = (frequency[i] * 100.0) / 36000;
System.out.printf("%d\t%d\t\n",i,frequency[i]);//this line here
}
}
}
First of all, your for loop is off by 1:
for (int i = 0; i <= 36000; i++) {
// ^
// remove this "=" or you will loop 36001 times
Your sum seems redundant, so remove that as well.
I think you just don't know how to format the output so that the floats correct to 2 d.p. right?
It's easy. Just add do %.2f!
Your printf will be like:
System.out.printf("%d\t%d\t%.2f\n",i,frequency[i], percentage);
Another problem with your code is that it might produce unaligned stuff. It also does not align the values to the right as the sample output shows. To fix this, you also just need to change the printf. Like this:
System.out.printf("%3d\t%9d\t%10.2f\n",i,frequency[i], percentage);
If you want to read more about how printf works, list here.
Stealing from this answer: we can use padRight which is defined as:
public static String padRight(String s, int n) {
return String.format("%1$-" + n + "s", s);
}
and do:
System.out.printf("Sum\tFrequency\tPercentage\n");
for (int i = 2; i < frequency.length; i++) {
String s = padRight(String.valueOf(i), 4);
String f = padRight(String.valueOf(frequency[i]), 12);
percentage = (frequency[i] * 100.0) / 36000;
String p = String.format("%.2f", percentage); // This formatting will keep two digits after the point
System.out.printf("%s%s%s\n", s ,f, p);
}
OUTPUT (example)
Sum Frequency Percentage
2 992 2.76
3 2031 5.64
4 3034 8.43
5 3947 10.96
6 4887 13.58
7 5948 16.52
8 4965 13.79
9 4051 11.25
10 3014 8.37
You can play with it and remove the \t from the first line and use spaces instead in order to create the amount of spacing you want between the columns and then pass the second parameter in the calls to padRight accordingly.
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.
I'm trying to make variable mark to decrement by 5 instead of 1. I want position 0 to remain the default input and after to decrement by 5 each time goes around the loop.
So if i input mark as 82 , the output should be :
(0)82; (1) 77; (2) 72 etc
import java.util.Scanner;
public class Late {
public static void main(String[] args) {
int mark;
int numberOfDays;
int counter = 4;
Scanner scn = new Scanner(System.in);
System.out.println("Input mark");
mark = scn.nextInt();
System.out.println("Input number of days");
numberOfDays = scn.nextInt();
for (int i = 0; i <= numberOfDays; i++) {
System.out.println("(" + i + ")" + mark--);
}
}
}
You already know about assignment, why not just do the most obvious?
mark = mark - 5;
In fact, the postfix -- and ++ operators are not the only way of manipulating the value of a variable. Even if they were, you could just write mark-- five times.
In most C-like languages (and Java is no exception), you can shorten this to
mark -= 5;
But the first variant is perfectly fine, too.
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!