449,312 Members | 1,877 Online Need help? Post your question and get tips & solutions from a community of 449,312 IT Pros & Developers. It's quick & easy.

# Average an array help

 P: n/a Kind of new at programming/vb.net. I'm doing this junky die roller program. Heres's what is supposed to happen: Roll 2 6-sided dies. Add rolls together put total in rolls(d6total). Display the number of 2 or 12 rolled, then display those numbers and average rolls. I didn't know how to do it exactly, but I came up with this. The obvious problem for me appears in loop (there may be other problems but they're not obvious to me). See below I used this in another sub to fill rolls array, based on a click event: ReDim Preserve rolls(UBound(rolls) + 1)' adds one to rolls dimension 'get number for rolls d6 = CInt(Int((6 * Rnd()) + 1)) d5 = CInt(Int((6 * Rnd())) + 1) d6Total = d5 + d6 'totals roll rolls(UBound(rolls)) = d6Total 'should keep record of rolls Private Sub btnSum_Click Dim i As Integer = 1 Dim temp, temp1 As Integer ' keeps running total of rolls Dim twelves, ones As Integer ' counts each 12 or 2 in rolls lstRollDis.Items.Clear() 'I expect the first pass through the loop will assign temp to roll(i). Then 'checks to see if a 12 or 2 is rolled then adds one to the total if yes. 'Since I want to average this array, Assign the value of temp to the running 'value of temp1. I think the value of i is causing out of bounds errors. I can't 'figure this out. It seems to make sense to me. For Each i In rolls temp = rolls(i) If temp = 12 Then twelves += 1 End If If temp = 2 Then ones += 1 End If i += 1 temp1 += temp Next With lstRollAverage.Items .Clear() .Add("Average roll " & Math.Round((temp1 / (i - 1)), 1) & " out of " & (i - 1)) 'I used (i-1) because loop pickups roll(0)as "0" .Add("You rolled " & twelves & " cars") .Add("You rolled " & ones & " snakes") .Add("and cowered " & cowers & " times") End With end sub Thanks for help, pointers, or suggestions. Nov 20 '05 #1
6 Replies

 P: n/a "J" wrote in message news:b9*************************@posting.google.co m... For Each i In rolls temp = rolls(i) If temp = 12 Then twelves += 1 End If If temp = 2 Then ones += 1 End If Use ElseIf here instead of two separate If... EndIf blocks i += 1 This is meaningless with a For Each loop. temp1 += temp Next With lstRollAverage.Items .Clear() .Add("Average roll " & Math.Round((temp1 / (i - 1)), 1) & " out of " & (i - 1)) This is the problem. Once you exit the For Each loop, i becomes 0/Nothing, even though you were incrementing it. So, you have to change to either: For i = 0 to ubound(rolls) .... Next OR Dim Cnt as Integer=0 For Each i In rolls .... Cnt+=1 Next Then use Cnt to get the average. -- Michael Caputo Programmer/Database Administrator Simon Economic Systems Ltd. Nov 20 '05 #3 