Matosh Matosh - 1 month ago 12
C# Question

2 x 10 random generated numbers have the same sum c#

I have 2 listboxes that i need to put 10 random generated numbers in. Then i need to calculate the sum of listbox 1 and the sum of listbox 2 and compare them to see which one is bigger. I do get different numbers in each listbox but for some reason the sum of the listboxes is always the same. How do i make it that the sum is different per listbox.
this i my code at the moment.

private void btnGo_Click(object sender, EventArgs e)
{

Random random = new Random();

listBox1.Items.Clear();
listBox2.Items.Clear();


for (int i = 0; i < 10; i++)
{

int nummer = random.Next(20);
int nummer2 = random.Next(20);
listBox1.Items.Add(nummer);
listBox2.Items.Add(nummer2);
}




if (addListbox1() > addListbox2())
{
textBox1.Text = "Listbox1 heeft de hoogste waarde namelijk " + Convert.ToString(addListbox1());
listBox1.BackColor = Color.Green;
listBox2.BackColor = Color.Red;


}

else
{

textBox1.Text = "Listbox2 heeft de hoogste waarde namelijk " + Convert.ToString(addListbox2());
listBox1.BackColor = Color.Red;
listBox2.BackColor = Color.Green;


}



}
private int addListbox1()
{
int listbox1total = 0;

for (int k = 0; k < listBox1.Items.Count;)
{
listbox1total += Convert.ToInt32(listBox1.Items[k++]);
}
return listbox1total;
}

private int addListbox2()
{
int listbox2total = 0;
int k = 0;

while(k < listBox2.Items.Count)
{
listbox2total += Convert.ToInt32(listBox1.Items[k++]);

}
return listbox2total;
}

Answer

You have a typo (an old story of copy + paste) in the code:

listbox2total += Convert.ToInt32(listBox1.Items[k++]);

should be

// please, notice "listBox2.Items"
listbox2total += Convert.ToInt32(listBox2.Items[k++]);

i.e. listbox2total should be the sum of listBox2.Items.

In order to avoid such errors, change the design, do not copy yourself, extract methods:

// Easiest, but not thread safe
private static Random random = new Random();

private static void FillBox(ListBox box, int count = 10) {
  box.Items.Clear();

  box.Items.AddRange(Enumerable
    .Range(0, count)
    .Select(x => (Object) random.Next(20))
    .ToArray());
}

private static int SumBox(ListBox box) {
  return box.Items
    .OfType<Object>()
    .Sum(x => Convert.ToInt32(x));
}

...

FillBox(listBox1);
FillBox(listBox2);

if (SumBox(listBox1) > SumBox(listBox2)) {
  ...
}
Comments