Tech Off Post

Single Post Permalink

View Thread: C# dice Roller
  • User profile image

    St23aM wrote:
    You said "on each loop add the current roll to the end of the string, and then tack the total on after the loop exits" This is exactly what im trying to figure out how to do. Could you make a suggestion in code?

    This is pretty much what the code I posted does. I guess I should have commented it for you..

    This time with comments.


      using System;
      using System.Text;

      public class EntryPoint {

        public static void Main(string[] args) {

          // roll two die with 6 faces
          Console.WriteLine(Dice.Roll(2, 6));

          // roll 4 die with 8 faces
          Console.WriteLine(Dice.Roll(4,Eye Rolling);

          Console.Write("Press ENTER to exit.");


      public class Dice {

        /// <summary>
        /// Rolls the specified number of die each with the specified number of
        /// sides and returns the result as a string, including the total.
        /// </summary>
        /// <param name="numberOfDice">The number of die to roll.</param>
        /// <param name="numberOfSides">The number of faces on each dice rolled.</param>
        /// <returns>A string containing the result of the roll.</returns>
        public static String Roll(Int32 numberOfDice, Int32 numberOfSides) {

          // don't allow a Number of Dice less than or equal to zero
          if (numberOfDice <= 0) {
            throw new ApplicationException("Number of die must be greater than zero.");

          // don't allow a Number of Sides less than or equal to zero
          if (numberOfSides <= 0) {
            throw new ApplicationException("Number of sides must be greater than zero.");

          // Create the random class used to generate random numbers.
          // See:
          Random rnd = new Random((Int32)DateTime.Now.Ticks);

          // Create the string builder class used to build the string
          // we return with the result of the die rolls.
          // See:
          StringBuilder result = new StringBuilder();

          // Declare the integer in which we will keep the total of the rolls
          Int32 total = 0;

          // repeat once for each number of dice
          for (Int32 i = 0; i < numberOfDice; i++) {

            // Get a pseudo-random result for this roll
            Int32 roll = rnd.Next(1, numberOfSides);

            // Add the result of this roll to the total
            total += roll;

            // Add the result of this roll to the string builder
            result.AppendFormat("Dice {0:00}:\t{1}\n", i + 1, roll);


          // Add a line to the result to seperate the rolls from the total

          // Add the total to the result
          result.AppendFormat("TOTAL:\t\t{0}\n", total);

          // Now that we've finished building the result, get the string
          // that we've been building and return it.
          return result.ToString();