Tech Off Post

Single Post Permalink

View Thread: C# dice Roller
  • User profile image
    jj5

    How about something like this. You might like to play around with the formatting of the output.

    John.

      using System;
      using System.Text;

      public class EntryPoint {

        [STAThread]
        public static void Main(string[] args) {

          Console.WriteLine(Dice.Roll(2, 6));
          Console.Write("Press ENTER to exit.");
          Console.ReadLine();

        }
      }

      public class Dice {

        public static String Roll(Int32 numberOfDice, Int32 numberOfSides) {

          if (numberOfDice <= 0) {
            throw new ApplicationException("Number of die must be greater than zero.");
          }

          if (numberOfSides <= 0) {
            throw new ApplicationException("Number of sides must be greater than zero.");
          }

          Random rnd = new Random((Int32)DateTime.Now.Ticks);

          Int32[] roll = new Int32[numberOfDice];

          for (Int32 i = 0; i < numberOfDice; i++) {

            roll[i] = rnd.Next(1, numberOfSides);

          }

          StringBuilder result = new StringBuilder();
          Int32 total = 0;

          for (Int32 i = 0; i < roll.Length; i++) {

            total += roll[i];
            result.AppendFormat("Dice {0:00}:\t{1}\n", i + 1, roll[i]);

          }

          result.AppendFormat("\t\t--\n");
          result.AppendFormat("TOTAL:\t\t{0}\n", total);

          return result.ToString();

        }

      }