Many pen-and-paper role-playing games (like Dungeons and Dragons) use dice to de
ID: 3593560 • Letter: M
Question
Many pen-and-paper role-playing games (like Dungeons and Dragons) use dice to determine damage, chances of success, and so forth. These games use polyhedral dice to generate numerical values in specific ranges. For example, an eight-sided die will generate values in the range 1-8, while a "normal" six-sided (cubic) die only generates numbers between 1 and 6. These dice are often represented using the following shorthand ndx, where n represents the number of dice to roll and dx represents the type For example, "2d6" means "roll two six-sided dice", while “1d12" means "roll one twelve-sided die". If you roll more than one die at a time, the values are added together to get the final result (so, for example, 2d6 would give you a value in the range 2-12). You may assume that n and x are always positive. There is no strict upper limit on the values of n and x, so you might encounter the (admittedly unlikely) input "204d130", which means "roll 204 130-sided dice" (thus producing an integer in the range 204-26520, inclusive). Define a Java method named rollDice() method, which takes a single String argument that represents a value in the format above (e.g., "4d12"). This method parses (breaks up) its argument and uses Math.random() (or Java's Random class) to return a randomly-generated integer value in the proper range. A pseudocode algorithm for this process is given below.Explanation / Answer
import java.util.Scanner;
public class Dice {
/**
* This method returns sum of dice values generated randomly by using
* Math.random(). Since Math.random() generates a random number between 0.0
* to 1.0 where 0.0 is inclusive and 1.0 is exclusive, we can follow this
* rule to generate random numbers inclusive of our range where minimum is
* always going to 1 and max depends on dice size.
*
* @param name
* - A dice name of format "ndx" where n is number of dices and x
* is number of sides of dice.
* @return - returns sum of all the random dice values.
*/
public static int rollDice(String name) {
String[] diceValues = name.split("d");
int numberOfDices = Integer.valueOf(diceValues[0]);
int diceSize = Integer.valueOf(diceValues[1]);
int sum = 0;
for (int i = 0; i < numberOfDices; i++) {
sum += (int) (Math.random() * (diceSize - 1) + 1);
}
return sum;
}
public static void main(String[] args) {
Scanner scanner; // For reading a line of input from the user.
scanner = new Scanner(System.in); // scanner reads from standard input.
System.out.print("Enter dice name: ");
String diceName = scanner.nextLine().trim();
System.out.println("Dice Value:- " + Dice.rollDice(diceName));
scanner.close();
}
}
Sample Output:
Enter dice name: 5d112
Dice Value:- 59
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.