1

I am trying to make a dice program. So when you click roll, it is supposed to roll two dice and add the sums and that's the number you roll. I need some help with this windows form program. Here is some code:

private int totalRolls;

private void btnRoll_Click(object sender, EventArgs e)
{
    totalRolls += 1;

    System.Random Int1 = new System.Random((int)System.DateTime.Now.Ticks);
    System.Random Int2 = new System.Random((int)System.DateTime.Now.Ticks);

    int randomInteger1 = Int1.Next(1, 7);
    int randomInteger2 = Int2.Next(1, 7);

    lblNumberRolled.Text = randomInteger1.ToString() + randomInteger2.ToString();

The code for lblNumberRolled.Text I don't think is right. That is the code to add both dice up to get final sum number of dice. But when I run it, it shows big numbers like 30 and stuff. It isn't adding or something.

The highest sum should be 12.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Gunnar
  • 113
  • 2
  • 9

3 Answers3

4

Change your code to:

lblNumberRolled.Text = (randomInteger1 + randomInteger2).ToString();

Explanation:

randomInteger1.ToString() +  randomInteger2.ToString() 

When randomInteger1 is 2 then you make a string of it it will be "2" + when randominterger2 is 1 after to String it is "1". When you concat these Strings with + you do "2" + "1" and that's 21 and not 3.

And there is another problem with your code: The Ticks object is of Type long and you cast it to int. So you loose information. This leads to that you will get most of the time the same seed for your both ints. And that leads to that you will get most of the timethe same random integers.

Putting a Thread.Sleep(20) between your random calls will fix it:

System.Random Int1 = new System.Random((int)System.DateTime.Now.Ticks);
Thread.Sleep(20);
System.Random Int2 = new System.Random((int)System.DateTime.Now.Ticks);
Dannydust
  • 763
  • 5
  • 8
2

This is because you are using a + for string. When you use '+' with strings the compiler thinks of it not as a math operation rather than a concatenation operator.

Try the following

Instead of

lblNumberRolled.Text = randomInteger1.ToString() + randomInteger2.ToString();

Try

lblNumberRolled.Text = Convert.ToString(randomInteger1+randomInteger2);
progrAmmar
  • 2,606
  • 4
  • 29
  • 58
0

You can do it like this:

Label lb = new Label();
Random random = new Random();
int ranNum1 = random.Next(1, 7); // random num 1-6
int ranNum2 = random.Next(1, 7); // random num 1-6
lb.Text = Convert.ToString(ranNum1 + ranNum2);
Form.Controls.Add(lb);

which means you want something like:

Random random = new Random();
randomInteger1 = random.Next(1,7);
randomInteger2 = random.Next(1,7);
lblNumberRolled.Text = Convert.ToString(randomInteger1 +randomInteger2);
Helmer
  • 116
  • 2