The array dont save my numbers - c#

I am trying to learn C# and doing some questions i googeld. This is the task to do:
*"Beginner level:
The task is to make
a dice game where the user throws 3
Each 12-sided dice (numbers
shall be randomly selected and stored in an array / field or list).
Add up the total of the dice and show on the screen.
Create a function / method that accepts a figure
(the total sum of the dice). Function / method
should return the text "Good throw" if the figure
is higher or equal to 20.
In all other cases, the text
"Sorry" is returned.
Call the function / method in the main method
and prints the total and the text.
Advanced level:
This is an extension of the task where you must use a class to simulate a dice. The user shall have the option of writing a x y-sided dice himself.
If the total sum of a roll of the dice generates a score that is> 50% of the maximum score, the words "good throw" is displayed.
This logic can be in your main method.
Create the class described in the class diagram and use appropriate
way in your code."*
The thing is that i cant get it to work, the array in my class do not save my numbers im typing in... I only get the reslut 0. I think i have just done some big misstake i cant see...
This is the Main code:
static void Main(string[] args)
{
List<Dice> _Dice = new List<Dice>();
int a = 0;
int times = int.Parse(Interaction.InputBox("Write how many times you want to repeat the game:"));
while (a != times)
{
int antThrow = int.Parse(Interaction.InputBox("Write how many times you want each dice to get thrown:"));
int xChoice = int.Parse(Interaction.InputBox("Write how many dice you want to throw:"));
int yChoice = int.Parse(Interaction.InputBox("Write how many sides you want each dice should have:"));
_Dice.Add(new Dice(xChoice,yChoice, antThrow));
a++;
}
int e = 1;
foreach (var item in _Dice)
{
Interaction.MsgBox(string.Format("Result of game {0}: {1}", e++, item.Tostring()));
}
}
This is the Dice class:
class Dice
{
static int _xChoice, _yChoice, _throw;
static List<int> sum = new List<int>();
static int w = 0;
static int _sum;
static int[,] dice = new int[_xChoice, _yChoice];
public string Tostring()
{
int half = _sum / 2;
if (half <= _sum/2)
{
return "Good throw!" + _sum;
}
else
{
return "Bad throw!";
}
}
void random()
{
Random rnd = new Random();
while (w != _throw)
{
for (int i = 0; i < dice.GetLength(0); i++)
{
for (int j = 0; j < dice.GetLength(1); j++)
{
dice[i, j] = rnd.Next(1, _yChoice);
_sum += dice[j, i];
sum.Add(_sum);
}
}
w++;
}
}
public Tarning(int Xchoice, int Ychoice, int throw)
{
_throw = thorw;
_xChoice = Xchoice;
_yChoice = Ychoice;
}
}

Your main problem is in the static keyword. Static field means that there's only
one field for all the instances, which is not your case: you need each instance of Dice has its own fields' values.
class Dice {
// no static here
private int _xChoice, _yChoice, _throw;
// no static here
private List<int> sum = new List<int>();
// no static here
private int w = 0;
// no static here
private int _sum;
// no static here
private int[,] dice = new int[_xChoice, _yChoice];
// BUT, you want a random generator for all the instances, that's why "static"
private static Random rnd = new Random();
// When overriding method mark it with "override"
// And Be Careful with CAPitalization:
// the method's name "ToString" not Tostring
public override string ToString() {
...
}
void random() {
// Do not create Random generator each time you call it:
// It makes the random sequences skewed badly!
// Istead use one generator for all the calls, see the code above
// private static Random rnd = new Random();
// Random rnd = new Random();
...
}
...

class Program
{
static void Main(string[] args)
{
var dice = new List<DiceLogic>();
int a = 0;
int times = GetTimes();
while (a != times)
{
int antThrow = GetAntThrow();
int xChoice = GetXChoice();
int yChoice = GetYChoice();
dice.Add(new DiceLogic(xChoice, yChoice, antThrow));
a++;
}
int e = 1;
foreach (var item in dice)
{
Console.WriteLine("Result of game {0}: {1}", e++, item.Tostring());
}
Console.ReadLine();
}
private static int GetTimes()
{
while (true)
{
Console.WriteLine("Write how many times you want to repeat the game:");
int times;
var result = int.TryParse(Console.ReadLine(), out times);
if (result) return times;
Console.WriteLine("Value must be a number.");
}
}
private static int GetAntThrow()
{
while (true)
{
Console.WriteLine("Write how many times you want each dice to get thrown:");
int antThrow;
var result = int.TryParse(Console.ReadLine(), out antThrow);
if (result) return antThrow;
Console.WriteLine("Value must be a number.");
}
}
private static int GetXChoice()
{
while (true)
{
Console.WriteLine("Write how many dice you want to throw:");
int getXChoice;
var result = int.TryParse(Console.ReadLine(), out getXChoice);
if (result) return getXChoice;
Console.WriteLine("Value must be a number.");
}
}
private static int GetYChoice()
{
while (true)
{
Console.WriteLine("Write how many sides you want each dice should have:");
int getXChoice;
var result = int.TryParse(Console.ReadLine(), out getXChoice);
if (result) return getXChoice;
Console.WriteLine("Value must be a number.");
}
}
}
public class DiceLogic
{
public string Tostring()
{
int maxScore = _diceSides*_dices;
if (_result >= maxScore / 2)
{
return "Good throw! " + _result;
}
return "Bad throw! " + _result;
}
private readonly int _dices;
private readonly int _diceSides;
private readonly int _throwDice;
private int _result;
private void CalculateResult()
{
var rnd = new Random();
for (int i = 0; i < _dices; i++)
{
int currentResult = 0;
for (int j = 0; j < _throwDice; j++)
{
currentResult = rnd.Next(0, _diceSides);
}
_result += currentResult;
}
}
public DiceLogic(int dices, int diceSides, int throwEachDice)
{
_dices = dices;
_diceSides = diceSides;
_throwDice = throwEachDice;
CalculateResult();
}
}
This is an example of how you could implement what they are asking, go through te code line by line with the debugger so you understand what is going on.

You never call the method random(). Therefore, the value of your member variable _sum is never changed and remains 0. You need to call the method random() somewhere. You should probably make it public and call it from your main method after you have set up all your dice.
Furthermore, your member variables in the Dice class are all static! That means that the different Dice instances will all share the same values. I think this is not intended. You should make the variables instance variables by removing the static modifier.

Your method Tarning is not called and it takes a reserved word “throw” [I believe it was supposed to be thorw]. The method is not void so it must return a type.
Random() is not invoked and does display anything.
Dice has not constructor that has 3 arguments within its braces but it’s declared as _Dice.Add(new Dice(xChoice,yChoice, antThrow));

Related

Function that writes out the sum only writes out 0

Problem: The sum writes out as 0. How do i make it so that the function Summa() writes out the actual sum out of the 10 numbers that user writes in?
This is probably extremely simple but im new to this :P
All of the things in the code weren't separate before but i wanted if i could move the sum part to it's own function
using System;
namespace Array
{
class Program
{
static void Main(string[] args)
{
int number;
int[] vektor = new int[10];
for (int i = 0; i < vektor.Length; i++)
{
Console.WriteLine("Enter a number");
number = Convert.ToInt32(Console.ReadLine());
vektor[i] = number;
}
Summa();
}
static void Summa()
{
int sum = 0;
int[] vektor = new int[10];
int i = 0;
sum = sum + vektor[i];
Console.WriteLine("The amount is " + sum);
}
}
}
You are creating a new array called vektor in the Summa() function, instead of using the one created in the main() function. Also you've to iterate through the array to find the sum
Change Summa to :
static void Summa(int[] vektor)
{
int sum = 0;
for(int i=0; i < vektor.Length; i++)
{
sum = sum + vektor[i];
}
Console.WriteLine("The amount is " + sum);
}
And change the function call in the main() to:
Summa(vektor);
You are summing a different array; you'd need to pass the array in:
static void Summa(int[] vektor)
{
int sum = 0;
foreach (var val in vektor)
sum += val;
// ^^^ or just use: var sum = vektor.Sum();
Console.WriteLine("The amount is " + sum);
}
/// ...
Summa(vektor);
So, you're not passing any information to your method "Summa", but you're instead creating a new Array.
So you need to pass the Array from your main method to you "summa" method.
namespace Array
{
class Program
{
static void Main(string[] args)
{
int number;
int[] vektor = new int[3];
for (int i = 0; i < vektor.Length; i++)
{
Console.WriteLine("Enter a number");
number = Convert.ToInt32(Console.ReadLine());
vektor[i] = number;
}
Summa(vektor);
}
static void Summa(int[] vektor)
{
int sum = 0;
foreach (var item in vektor)
{
sum += vektor[item];
}
Console.WriteLine("The amount is " + sum);
}
}
}
Also, using foreach loops will make your life much easier in the future.
https://www.w3schools.com/cs/cs_for_loop.asp
When you're unsure what your program is doing and don't know why it isn't working like it should. Try using the debug feature.
If you're using Visual Studio you can access it by pressing F11.
Lycka till med studierna!

C# exclude numbers from a list in random generation

I am making a tic tac toe game and I am making it to be unbeatable
but first I have to let the computer know the rules.
I'm stuck in a step that is => when it's the computer's turn and we have just started the game so no win case so it's up to the computer to generate a random number that will be the computer's choice ( the block where he mark X or O )
so I need it to generate a number from 1 to 9 but by excluding the already used blocks ( numbers ).
I tried doing that by making a list and adding a number every time the human player used a block but I can't find a way to use those numbers from the list as exclusion for the random choice of the computer.
Here is what I tried and thnx in advance:
//random
List<int> cas = new List<int>();
if (c1 == true)
{
cas.Add(1);
}
if (c2 == true)
{
cas.Add(2);
}
if (c3 == true)
{
cas.Add(3);
}
if (c4 == true)
{
cas.Add(4);
}
if (c5 == true)
{
cas.Add(5);
}
if (c6 == true)
{
cas.Add(6);
}
if (c7 == true)
{
cas.Add(7);
}
if (c8 == true)
{
cas.Add(8);
}
if (c9 == true)
{
cas.Add(9);
}
for (int i = 0; i < cas.Count; i++)
{
random_except_list(cas[]);
}
public static int random_except_list(int[] x)
{
Random r = new Random();
int result = r.Next(1, 9 - );
for (int i = 0; i < x.Length; i++)
{
if (result < x[i])
return result;
result++;
}
return result;
}
Lets have possible places to use:
List<int> possible = Enumerable.Range(1,9).ToList(); // create a list and add 1-9
and used places:
List<int> used = new List<int>();
Random rnd = new Random();
Now everytime we generate a random number in the range of possible list count as index and remove it from there and move it to used:
int index = rnd.Next(0, possible.Count);
used.Add(possible[index]);
possible.RemoveAt(index);
for user its just enough to check if it exists in the used so the acceptable number should be:
!used.Any(x=> x== NumberUserHaveChosen)
So the first time the random number can be 0-8 (as possible.Count==9) and take from it at random index.
the second time the random number can be 0-7 (as possible.Count==8) and take from it at random index.
and so on... while the possible.Count != 0
in this case there is no need to generate random numbers several times that finally it won't exist in our used List.
Several years ago I was working on a Sudoku algorithm, and what I was trying to achieve was to generate a valid solved sudoku table in minimum time possible, i get to the conclusion that I should replace the algorithm that each time I generate a number I have to check some lists to make sure the number was not generated before, as count of numbers were increasing these comparisons would become more and more. for example when only the number 4 is remaining, I should generate random numbers till I get 4. so I used this approach and the result was amazing.
I think you should do something like this:
public static int random_except_list(List<int> x)
{
Random r = new Random();
int result = 0;
while (true)
{
result = r.Next(1, 10);
if (!x.Contains(result))
return result;
}
}
Just trying to use what you have written (more or less), but changing the method to take a List<int> which is what you are building, I would write the method using LINQ like this (except I would create a static Random variable and keep it between calls):
public static int random_except_list(List<int> x) => Enumerable.Range(1, 9).Where(n => !x.Contains(n)).ToList()[new Random().Next(0, 9 - x.Count)];
However, you can implement the same idea in a more explicit way using procedural code:
public static int random_except_list_explicit(List<int> x) {
// First, generate a list of possible answers by skipping the except positions in x
var possibles = new List<int>();
for (int i = 1; i <= 9; i++)
if (!x.Contains(i))
possibles.Add(i);
// now pick a random member of the possible answers and return it
return possibles[new Random().Next(0, possibles.Count)];
}
I believe it is better to work with positions left. So user or computer select from all open positions:
using System;
using System.Collections.Generic;
class app
{
public static int random_except_list(List<int> openPositions)
{
Random r = new Random();
int index = r.Next(openPositions.Count - 1);
int result = openPositions[index];
openPositions.RemoveAt(index);
return result;
}
static void Main()
{
List<int> openPositions = new List<int>();
for (int i = 1; i < 10; i++)
{
openPositions.Add(i);
}
bool turn = false;
while (openPositions.Count > 0)
{
foreach (int value in openPositions)
{
Console.Write(value + " ");
}
Console.WriteLine();
if (!turn)
{
while (true)
{
Console.WriteLine("Choose your Position");
ConsoleKeyInfo key = Console.ReadKey();
int num = (int)key.KeyChar - 48;
if (openPositions.Contains(num))
{
openPositions.Remove(num);
Console.WriteLine();
break;
}
else Console.Write(" is not Valid: ");
}
}
else
{
int compPos = random_except_list(openPositions);
Console.WriteLine("Computer choose: " + compPos);
}
turn = !turn;
}
Console.WriteLine("No positions left");
Console.ReadKey();
}
}

Noob needing help on breaking out of loop

I'm very sorry this is such an easy question, I'm just starting out. I've created code that allows a user to enter a number of random dice rolls, and outputs the sum of those rolls. I've now been asked to create a loop that repeats these steps, including the prompt, until the user types 'quit'. My issue is that my code converts the string to an integer, so typing anything kills the code. Any tips of how to insert the loop and break? My code is:
static void Main(string[] args)
{
Random random = new Random();
Console.WriteLine("Enter a number of dice to roll:");
string numberDiceString = Console.ReadLine();
int numberDice = Convert.ToInt32(numberDiceString);
int total = 0;
for (int index = 0; index < numberDice; index++)
{
int DieRoll = random.Next(6) + 1;
total += DieRoll;
}
Console.WriteLine(total);
Console.ReadKey();
}
I wouldn't use a "while(true)" statement. As someone pointed out in the comments i would prefer using the right condition in there.
That being said i would do it this way:
static void Main(string[] args)
{
Random random = new Random();
string numberDiceString;
int numberDice;
Console.WriteLine("Enter a number of dice to roll:");
while ((numberDiceString = Console.ReadLine()) != "quit")
{
bool parsed = int.TryParse(numberDiceString, out numberDice);
if (!parsed)
{
//Handle the error. The user input was not a number or "quit" word
break;
}
int total = 0;
for (int index = 0; index < numberDice; index++)
{
int DieRoll = random.Next(6) + 1;
total += DieRoll;
}
Console.WriteLine(total);
Console.WriteLine("Enter a number of dice to roll:");
}
}
I have to say that i prefer this way because you can easily see when the loop will stop. Also i added an error handling that you should be doing (What happen if the user enters any words that are not numbers?).
Hope this helps.
This change should be fairly simple. What you need to do is to create a while loop, and then a check before you actually parse for an int. The psuedocode for this would be something like.
while(true) {
//Ask for input
//Check if it equals "quit"
//If so -> break;
//If not convert to int
//For Loop for dice rolls
//Print Total
}
I'm sure it could be a little more elegant than this, and you would want to put some more checks to make sure that invalid input doesn't crash the program, but it should get the job done.
This is a very simple solution that shows how to parse the user input.
using System;
namespace Simpleton
{
class Program
{
static public int GetChoice()
{
int choice = 0;
while (true)
{
Console.Write("Enter number of rolls or \"quit\" to finish: ");
var answer = Console.ReadLine();
if (String.Compare(answer, "quit", true) == 0)
{
return 0; // Done
}
if (Int32.TryParse(answer, out choice))
{
return choice;
}
}
}
static void Main(string[] args)
{
var choice = 0;
while ((choice = GetChoice()) > 0)
{
Console.WriteLine($"You'll be looping {choice} times.");
for (int tries = 0; tries < choice; tries++)
{
// Looping
}
}
}
}
}
Try this code:
static void Main(string[] args)
{
Random random = new Random();
while(true)
{
String numberDiceString = "";
int numberDice = 0;
Console.WriteLine("Enter a number of dice to roll:");
numberDiceString = Console.ReadLine();
if (numberDiceString == "quit") { return; }
int total = 0;
if (Int32.TryParse(numberDiceString, out numberDice))
{
total = 0;
for (int index = 0; index < numberDice; index++)
{
int DieRoll = random.Next(6) + 1;
total += DieRoll;
}
}
Console.WriteLine(total);
}
}
I'm not a C# programmer, but you can test for "quit" explicitly and use a goto
BeginLoop:
Console.WriteLine("Enter a number of dice to roll:");
string numberDiceString = Console.ReadLine();
if (numberDiceString == "quit")
{
goto EndLoop;
}
int numberDice = Convert.ToInt32(numberDiceString);
/* Rest of code you want to do per iteration */
goto BeginLoop;
EndLoop:

C# : Console.Read() does not get the "right" input

I have the following code:
The actual problem is the "non-quoted" code.
I want to get the player amount (max = 4), but when I ask via Console.Read() and I enter any Int from 1 to 4 I get as value: 48 + Console.Read().
They only thing how I can get the "real" input is using Console.ReadLine(), but this does not give me an Integer, no it returns a string, and actually do not know how to convert String (Numbers) to Integers in C#, because I am new, and because I only found ToString() and not ToNumber.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace eve_calc_tool
{
class Program
{
int players;
int units;
int active_units;
int inactive_units;
int finished_units;
int lastDiceNumber = 0;
bool game_state;
public static void Main(string[] args)
{
int count_game = 0;
//Console.Title = "Mensch ärger dich nicht";
//Console.WriteLine("\tNeues Spiel wird");
//Console.WriteLine("\t...geladen");
//System.Threading.Thread.Sleep(5000);
//Console.Clear();
//Console.WriteLine("Neues Spiel wird gestartet, bitte haben sie etwas Geduld");
//Console.Title = "Spiel " + count_game.ToString();
//Console.Clear();
//string prevText = "Anzahl der Spieler: ";
//Console.WriteLine(prevText);
string read = Console.ReadLine();
/*Program game = new Program();
game.players = read;
game.setPlayers(game.players);
if (game.players > 0 && 5 > game.players)
{
game.firstRound();
}*/
string readagain = read;
Console.ReadLine();
}
/*
bool setPlayers(int amount)
{
players = amount;
if (players > 0)
{
return true;
}
else
{
return false;
}
}
bool createGame()
{
inactive_units = units = getPlayers() * 4;
active_units = 0;
finished_units = 0;
game_state = true;
if (game_state == true)
{
return true;
}
else
{
return false;
}
}
int getPlayers()
{
return players;
}
private static readonly Random random = new Random();
private static readonly object syncLock = new object();
public static int RandomNumber(int min, int max)
{
lock (syncLock)
{ // synchronize
return random.Next(min, max);
}
}
int rollDice()
{
lastDiceNumber = RandomNumber(1,6);
return lastDiceNumber;
}
int firstRound()
{
int[] results = new int[getPlayers()];
for (int i = 0; i < getPlayers(); i++)
{
results[i] = rollDice();
}
Array.Sort(results);
return results[3];
}
*/
}
}
You can use
int convertedNumber = int.parse(stringToConvert)
or
int convertedNumber;
int.TryParse(stringToConvert, out covertedNumber)
to convert strings to integers.
You should really use TryParse instead so that you can catch if the user doesn't input a number. int.Parse will throw an exception if it tries to convert a string that is not numeric.
int convertedNumber = 0;
if (!int.TryParse(stringToConvert, out convertedNumber))
{
// this code will execute if the user did not put
// in an actual number. For example, if the user entered "a".
}
The TryParse method returns a boolean value which will tell you whether the conversion was successful. If it was successful, the converted value will be passed through the out parameter.
To convert your string to an integer, use int.Parse(yourString).
The reason you get "48 + Console.ReadKey" is that Console.ReadKey returns the code of the key that was pressed - in this case, the ANSI value of the number character that was pressed.

dice rolling in C# console application giving incorrect totals

I am writing dice roller program in C# console. I am giving two input
Enter the size of the dice and
Enter how times you want to play.
Suppose dice size is 6 and 10 times i have played.
Output is coming:
1 was rolled 2 times
2 was rolled 7 times
3 was rolled 8 times
4 was rolled 7 times
5 was rolled 4 times
6 was rolled 5 times
Total: 33 (its not fixed for every execution this no will be changed)
But my requirement was this total always should be number of playing times. Here I am playing 10 times so the total should be 10 not 33. It should happen for every new numbers... If I play 100 times sum or total should be 100 only not any other number. rest all will be remain same, in my programing not getting the expected sum. Please somebody modify it. Here is my code:
Dice.cs:
public class Dice
{
Int32 _DiceSize;
public Int32 _NoOfDice;
public Dice(Int32 dicesize)
{
this._DiceSize = dicesize;
}
public string Roll()
{
if (_DiceSize<= 0)
{
throw new ApplicationException("Dice Size cant be less than 0 or 0");
}
if (_NoOfDice <= 0)
{
throw new ApplicationException("No of dice cant be less than 0 or 0");
}
Random rnd = new Random();
Int32[] roll = new Int32[_DiceSize];
for (Int32 i = 0; i < _DiceSize; i++)
{
roll[i] = rnd.Next(1,_NoOfDice);
}
StringBuilder result = new StringBuilder();
Int32 Total = 0;
Console.WriteLine("Rolling.......");
for (Int32 i = 0; i < roll.Length; i++)
{
Total += roll[i];
result.AppendFormat("{0}:\t was rolled\t{1}\t times\n", i + 1, roll[i]);
}
result.AppendFormat("\t\t\t......\n");
result.AppendFormat("TOTAL: {0}", Total);
return result.ToString();
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter no of dice size");
int dicesize = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("How many times want to play");
int noofplay=Convert.ToInt32(Console.ReadLine());
Dice obj = new Dice(dicesize);
obj._NoOfDice = noofplay;
obj.Roll();
Console.WriteLine(obj.Roll());
Console.WriteLine("Press enter to exit");
Console.ReadKey();
}
}
It looks to me like you're getting the math backwards... shouldn't it be:
// to capture just the counts
int[] roll = new int[_DiceSize];
for (int i = 0; i < _NoOfDice; i++)
{
roll[rnd.Next(roll.Length)]++;
}
Or if you want the actual rolls:
// to capture individual rolls
int[] roll = new int[_NoOfDice];
for (int i = 0; i < _NoOfDice; i++)
{
roll[i] = rnd.Next(_DiceSize) + 1; // note upper bound is exclusive, so +1
}
You are creating a new Random instance on each iteration. This is not a good thing as it will affect the uniform distribution of results. Keep the Random instance in a field instead of creating a new one every time.
public class Dice {
private Random rnd = new Random();
// ... don't create a new random in `Roll` method. Use `rnd` directly.
}
First of all, the following for-loop is wrong:
for (Int32 i = 0; i < _DiceSize; i++)
{
roll[i] = rnd.Next(1,_NoOfDice);
}
Obviously you switched _DiceSize and _NoOfDice. The correct loop would look like
for (Int32 i = 0; i < _NoOfDice; i++)
{
roll[i] = rnd.Next(1,_DiceSize);
}
Because of that, the line
Int32[] roll = new Int32[_DiceSize];
has to be changed to
Int32[] roll = new Int32[_NoOfDice];
Maybe you should think about renaming these variables, so it's more clearly, which means what.
If you modify your code that way, you will mention that your analisys won't work that way you implemented it. Actually, what you are showing is the result of each throw, which is not what you want, if I understood you right.
UPDATE:
Sorry, I misunderstood you. You do want to show the result for every roll. So, why don't you just move the StringBuilder.AppendFormat to your "rolling-for-loop"?
UPDATE #2:
For me, the following Die-class works exactly the way you want it:
public class Die
{
private int maxValue;
private int numberOfRolls;
private Random random;
public Die(int maxValue, int numberOfRolls)
{
this.maxValue = maxValue;
this.numberOfRolls = numberOfRolls;
this.random = new Random();
}
public string Roll()
{
StringBuilder resultString = new StringBuilder();
for (int i = 0; i < this.numberOfRolls; i++)
{
resultString.AppendFormat("Roll #{0} - Result: {1}" + Environment.NewLine, i + 1, this.random.Next(1, maxValue + 1));
}
return resultString.ToString();
}
}
Hope I could help you.
This is the full code you have to use, according to Mehrdad and Marc Gravell.
Have fun.
public class Dice
{
private Random rnd = new Random();
Int32 _DiceSize;
public Int32 _NoOfDice;
public Dice(Int32 dicesize)
{
if (dicesize <= 0)
{
throw new ApplicationException("Dice Size cant be less than 0 or 0");
}
this._DiceSize = dicesize;
}
public string Roll()
{
if (_NoOfDice <= 0)
{
throw new ApplicationException("No of dice cant be less than 0 or 0");
}
// to capture just the counts
int[] roll = new int[_DiceSize];
for (int i = 0; i < _NoOfDice; i++)
{
roll[rnd.Next(roll.Length)]++;
}
StringBuilder result = new StringBuilder();
Int32 Total = 0;
Console.WriteLine("Rolling.......");
for (Int32 i = 0; i < roll.Length; i++)
{
Total += roll[i];
result.AppendFormat("{0}:\t was rolled\t{1}\t times\n", i + 1, roll[i]);
}
result.AppendFormat("\t\t\t......\n");
result.AppendFormat("TOTAL: {0}", Total);
return result.ToString();
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter no of dice size");
int dicesize = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("How many times want to play");
int noofplay = Convert.ToInt32(Console.ReadLine());
Dice obj = new Dice(dicesize);
obj._NoOfDice = noofplay;
Console.WriteLine(obj.Roll());
Console.WriteLine("Press enter to exit");
Console.ReadKey();
}
}

Categories