Simple, Quality, Awesome Software

Die Rolling

Below is the complete code for the Die Rolling Try It Out! problem.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DieRolling
{
    class Program
    {        
        static void Main(string[] args)
        {
            // Creates a variable that can store things with the Random
            // type. This also creates a new Random object and puts it in the
            // variable. This Random object uses the default parameter-less
            // constructor.
            // Remember that classes are reference types, so the data that
            // is buried inside of this Random object is stored on the heap.
            Random random = new Random();

            // Gets the number of dice to roll here.
            Console.WriteLine("Number of dice to roll: ");
            int count = Convert.ToInt32(Console.ReadLine());

            // Simulate a die roll for each of the dice that were requested.
            int total = 0;
            for (int index = 0; index < count; index++)
            {
                // The Next method is a part of the Random class. You can
                // call it if you have a Random typed object, which we do.
                int roll = random.Next(6) + 1;
                total += roll;

                // We print out the individual die rolls, one at a time.
                // The way these are being printed out (2+3+4+6=15), I have
                // it print out an extra plus, only if we're not on the last
                // one.
                if (index != count - 1)
                {
                    Console.Write(roll + "+");
                }
                else
                {
                    Console.Write(roll);
                }
            }

            // Print the sum.
            Console.WriteLine("=" + total);

            Console.ReadKey();
        }
    }
}