Wrong sum calculation of objects in array - vb.net

I received code with an object (we'll call it Obj) with a property named Number. An array of these objects is defined with 40 objects in indexes 0..39. I don't need object at index 0.
The code has a static variable saving the sum of all Number's of Obj's in the array. This variable is initialized only once. Right after the Number values themselves are defined.
It usually works, but sometimes I log an exception (which I haven't been able to reproduce) with values of different objects and I see there the value of NumberAll is wrong (I've recently logged 1722 and 2134. Not that it should matter - but the only common prime factor for them is 2. should be 1554, if you were wondering, you can check me below :) ).
EDIT: The exception is an Index was outside the bounds of the array on the loop brought in the code below - a direct effect of this issue.
I've tried two methods of summing, brought below.
Relevant code follows. There is nowhere else in the code that a value is assigned to NumberAll.
Static NotFirstTime As Boolean, NumberAll As Integer
If NotFirstTime = False Then GoTo Data
sPoint: 'Code and more code
' ...
' ...
breakValue = someValue Mod NumberAll
Sum = 0
I = 1
Try
Do
If Sum + myArray(I).Number >= breakValue Then
Exit Do
End If
Sum = Sum + myArray(I).Number
I = I + 1
Loop
Catch ex As Exception
'log error and variable data - breakValue is larger than Sum will ever get
'hence the loop reaches the point of trying myArray(40) which doesn't exist
End Try
' ...
Data:
NotFirstTime = True
myArray(1).Number = 37
myArray(2).Number = 34
myArray(3).Number = 44
myArray(4).Number = 31
myArray(5).Number = 59
myArray(6).Number = 26
myArray(7).Number = 33
myArray(8).Number = 28
myArray(9).Number = 20
myArray(10).Number = 13
myArray(11).Number = 92
myArray(12).Number = 65
myArray(13).Number = 71
myArray(14).Number = 22
myArray(15).Number = 22
myArray(16).Number = 42
myArray(17).Number = 26
myArray(18).Number = 26
myArray(19).Number = 33
myArray(20).Number = 34
myArray(21).Number = 22
myArray(22).Number = 19
myArray(23).Number = 85
myArray(24).Number = 72
myArray(25).Number = 47
myArray(26).Number = 40
myArray(27).Number = 47
myArray(28).Number = 54
myArray(29).Number = 48
myArray(30).Number = 44
myArray(31).Number = 37
myArray(32).Number = 34
myArray(33).Number = 44
myArray(34).Number = 9
myArray(35).Number = 57
myArray(36).Number = 37
myArray(37).Number = 19
myArray(38).Number = 13
myArray(39).Number = 68
NumberAll = 0
'Only one of the following methods is used. They seem to give the same result. The bug exists in both.
'Method one
For I = 1 To 39 'E מספר המסכתות
NumberAll = NumberAll + myArray(I).Number
Next I
'Method two
Dim myList As List(Of Obj) = New List(Of Obj)(myArray)
NumberAll = myList.Sum(Function(b) b.Number)
NumberAll -= myArray(0).Number
GoTo sPoint

Related

strword can be how can split used vbcrlf

How can split that items? I don't have anything else to do, which is what the textbox results look like and I don't know how to extract the values correctly from it.
Dim lines() As String = TxtResultToString1.Lines
For i As Integer = 1 To lines.Length - 1
Dim strWords = lines(i).Split(vbCrLf)
MsgBox(strWords(0))
Next
Items: this looks like it in the textbox
{ item = , Count = 1 }
{ item = 13, Count = 1 }
{ item = 17, Count = 1 }
{ item = 31, Count = 1 }
{ item = 5, Count = 1 }
{ item = 8, Count = 1 }
{ item = 77, Count = 2 }
{ item = 68, Count = 1 }
{ item = 21, Count = 1 }
{ item = 71, Count = 1 }
{ item = 40, Count = 1 }
{ item = 14, Count = 1 }
{ item = 49, Count = 1 }
{ item = 45, Count = 1 }
{ item = 29, Count = 1 }
{ item = 36, Count = 1 }
{ item = 44, Count = 1 }
In another textbox I want to do the following:
Textbox2.Lines=
13 17 31
17 31 5
31 5 8
8 77 68
68 21 71
21 71 40
71 40 14
40 14 49
14 49 45
49 45 29
45 29 36
29 36 44
First I parsed the lines in the text box to extract the item value. I split the line by the comma and then element (0) is split by the equals sign and trimmed. The result is add to the list. Then looping through the list I use a string builder to build the new lines. The minus 3 avoides an index out of range.
Private Sub ItemArrangement()
Dim lst As New List(Of String)
Dim lines = TextBox1.Lines
For i = 1 To TextBox1.Lines.Count - 1
Dim num = lines(i).Split(","c)(0).Split("="c)(1).Trim
lst.Add(num)
Next
Dim sb As New StringBuilder
For i = 0 To lst.Count - 3
sb.AppendLine($"{lst(i)} {lst(i + 1)} {lst(i + 2)}")
Next
TextBox2.Text = sb.ToString
End Sub
What you showed as output missed the line starting with 5. If this was intentional you will have to adjust the code.
My output in TextBox2 looked like this.
13 17 31
17 31 5
31 5 8
5 8 77
8 77 68
77 68 21
68 21 71
21 71 40
71 40 14
40 14 49
14 49 45
49 45 29
45 29 36
29 36 44

Declare (automatically) variables in vba

Is it possible to declare (automatically) variables in vba and with increasing number?
I have to Dim 50 variables, like Var1 till Var50
Is it possible with vba code
All my efforts (for next with concatenate) didn't work
The result should be;
Dim Var1 as integer
Dim Var2 as integer
.
.
Dim Var50 as integer
Use
Dim Var(1 to 50) as integer
Then you can set values for each like so
Var(1) = 1
Var(2) = 2
Var(3) = 3
Var(4) = 4
Var(5) = 5
Var(6) = 6
Var(7) = 7
Var(8) = 8
Var(9) = 9
Var(10) = 10
Var(11) = 11
Var(12) = 12
Var(13) = 13
Var(14) = 14
Var(15) = 15
Var(16) = 16
Var(17) = 17
Var(18) = 18
Var(19) = 19
Var(20) = 20
Var(21) = 21
Var(22) = 22
Var(23) = 23
Var(24) = 24
Var(25) = 25
Var(26) = 26
Var(27) = 27
Var(28) = 28
Var(29) = 29
Var(30) = 30
Var(31) = 31
Var(32) = 32
Var(33) = 33
Var(34) = 34
Var(35) = 35
Var(36) = 36
Var(37) = 37
Var(38) = 38
Var(39) = 39
Var(40) = 40
Var(41) = 41
Var(42) = 42
Var(43) = 43
Var(44) = 44
Var(45) = 45
Var(46) = 46
Var(47) = 47
Var(48) = 48
Var(49) = 49
Var(50) = 50

vb.net Getting numbers from array horizontally and vertically?

I have this crazy array.
ReDim arrayDeCeldas(filas - 1, columnas - 1)
For i = 0 To filas - 1
For j = 0 To columnas - 1
arrayDeCeldas(i, j) = i & j
Debug.Write(arrayDeCeldas(i, j) & " ")
Next j
Debug.WriteLine("")
Next i
And I'm trying to link it to a number of conditions and is not well to do
I'm trying to try to get 6 index from array
The number can't repeat and it are pick horizontally or vertically randomly
0 1 2 3 4 5 6 7
10 11 12 13 14 15 16 17
20 21 22 23 24 25 26 27
30 31 32 33 34 35 36 37
40 41 42 43 44 45 46 47
This example about i'm try.
It can be seen, there are a total of 6 items with different sizes
Actually my code, it's getting huge
Private Sub setBarco()
Dim numeroRandom As New System.Random()
Dim indiceA, indiceB As Integer
For b = 1 To barcos
Randomize()
Dim value As Integer = CInt(Int((2 * Rnd() + 1)))
indiceA = numeroRandom.Next(0, filas)
indiceB = numeroRandom.Next(0, columnas)
Select Case b
Case 1
If arrayDeCeldas(indiceA, indiceB) = 0 Then
arrayDeCeldas(indiceA, indiceB) = b & 1
End If
Case 2
Select Case value
Case 1
For c = 0 To 1
If indiceB + c < columnas Then
If arrayDeCeldas(indiceA, indiceB + c) = 0 Then
arrayDeCeldas(indiceA, indiceB + c) = b & c
End If
Else
If arrayDeCeldas(indiceA, indiceB - c) = 0 Then
arrayDeCeldas(indiceA, indiceB - c) = b & c
End If
End If
Next
Case 2
For c = 0 To 1
If indiceA + c < filas Then
If arrayDeCeldas(indiceA + c, indiceB) = 0 Then
arrayDeCeldas(indiceA + c, indiceB) = b & c
Else
End If
Else
End If
Next
End Select
Case 3
Case 4
Case 5
Case 6
End Select
Next b
End Sub
Based on your comment-reply, I understand the program must:
Pick at random any six elements from a 2D-array, and each element or value must be selected only once.
That's fairly straightforward: here's a pseudo-code implementation:
Perform some initial computation:
Get the bounds of the 2D array
Seed a random number generator:
Create a HashSet instance
Get six pairs of coordinates:
Loop continuously until HashSet has 6 elements in it:
Generate a coordinate pair within the bounds of the array found in Step 1.
Get the value from the coordinate pair
Check to see if we've seen the value before (by looking at the HashSet). If we've not seen it before, then add it to the HashSet and continue, otherwise ignore it and try again.
Return the contents of the HashSet
In C# this would be:
Int32[,] numbers = new Int32[] { ... };
Int32 maxY = numbers.GetUpperBound(0); // y-axis in dimension 0
Int32 maxX = numbers.GetUpperBound(1); // x-axis in dimension 1
Random rng = new Random();
HashSet<Int32> values = new HashSet<Int32>();
while( values.Count < 6 ) {
Int32 x = rng.Next( maxX + 1 ); // Random.Next is upperbound exclusive, hence +1
Int32 y = rng.Next( maxY + 1 );
Int32 value = numbers[ y, x ];
if( !values.Contains( value ) ) values.Add( value );
}
return values.ToArray();
Note that by keeping track of observed values, instead of coordinates, we can simultaneously avoid duplicate values and duplicate coordinates: as duplicate coordinates will give you duplicate values anyway.

Nested FOR loops in VBA

I am attempting to impliment a nested FOR loop in excel. Then interior loop does not seem to be executing in the code. Is the error syntatical? What's going on here?
Sub Statistics()
Dim cc As Integer
Dim i As Integer
i = 4
cc = 0
For cc = 0 To 4
For i = 4 To -4
If Sheets("Significance").Cells(4 + cc, 13 - i) = 1 Then Sheets("Output Database").Cells(8 + currevent, 7 + cc) = i
Next i
Next cc
'Rates
i = 4
cc = 0
For cc = 0 To 4
For i = 4 To -4
If Sheets("Significance").Cells(14 + cc, 13 - i) = 1 Then Sheets("Output Database").Cells(8 + currevent, 23 + cc) = i
Next i
Next cc
End Sub
The loop referring to the i variable needs to specify that i is decreasing:
For i = 4 To -4 Step -1

Error in assigning object of nullable type in vb.net

I am new to VB.net and facing a strange situation. I have a structure that contains another structure. The inner structure is nullable. Now wht I do is something like the following. I create a new instance of the inner structure, set the member variables and assign the whole structure to the inner structure of the parent. But it is giving an error. The assignment is not successful. If I try to peek into the structure in the watch window, it says "property evaluation failed" for the HasValue and Value properties.
Dim testData As List(Of TestData) = Nothing
Dim testData_List1 As New TestData
With testData_List1.commonTestParam
.AccuchekActiveEnergy = 2.56
.AccuchekActiveEnergyUnit = ActiveEnergyUnit.KiloWattHour
.AccuchekApparentEnergy = 34.56
.AccuchekApparentEnergyUnit = ApparentEnergyUnit.VoltAmpereHour
.AccuchekFrequency = 1
.AccuchekRange = "20474 ewr 34324"
.AccuchekType = AccuchekType.AccuchekOne
.ActiveLoadRPhase = 145
.AvgActiveLoad = 2.56
.AvgActiveLoadUnit = ActiveLoadUnit.Watt
.AvgPowerFactor = 0
.AvgPowerFactorType = PowerFactorType.PFLag
.ConditionalFlag1 = 0
.ConsumerNo = "343122050242"
.CurrentRPhase = 1
.GeneralFlag1 = 0
.InstantaneousPFRPhase = 2
.ManufacturingYear = 2009
.MeterActiveEnergy = 258.89
.MeterActiveEnergyUnit = ActiveEnergyUnit.KiloWattHour
.MeterActiveError = 20
.MeterApparentError = 14
.MeterConstant = 3200
.MeterConstantUnit = MeterConstantUnit.RevsPerkVAh
.MeterMake = "DS"
.MeterSNo = "6563402"
.MeterTypeAndClass = MeterTypeAndClass.MTCElectorMechWith20
.MTFID = "123456789"
.NoofTestRevolutions = 100
.PulseCriteria = 0
.RatedBasic = 25
.RatedMax = 30
.RatedVoltage = 15
.ReactiveCurrentRPhase = 145
.RemarkID = 0
.TestDateAndTime = "100320101545"
.TestDuration = 2145
.TesterCode = 0
.TestID = "147852"
.TestMode = TestMode.TMOpticalScanner
.TestNumber = 0
.VoltageRPhase = 145
End With
Dim accuchek3TestParameters1 As New Accuchek3PhaseTestParameters
With accuchek3TestParameters1
.AccuchekReactiveLagEnergy = 2.46
.AccuchekReactiveLagEnergyUnit = ReactiveEnergyUnit.KiloVoltAmpereReactiveHour
.AccuchekReactiveLeadEnergy = 2.56
.AccuchekReactiveLeadEnergyUnit = ReactiveEnergyUnit.KiloVoltAmpereReactiveHour
.ActiveLoadBPhase = 14
.ActiveLoadYPhase = 15
.AvgApparentLoad = 10
.AvgApparentLoadUnit = ApparentLoadUnit.KiloVoltAmpere
.AvgReactiveLagLoad = 14
.AvgReactiveLagLoadUnit = ReactiveLoadUnit.KiloVoltAmpereReactive
.AvgReactiveLeadLoad = 15
.AvgReactiveLeadLoadUnit = ReactiveLoadUnit.KiloVoltAmpereReactive
.ConditionalFlag2 = 0
.ConditionalFlag3 = 0
.CTRatio = 1.23
.CurrentBPhase = 10
.CurrentYPhase = 11
.InstantaneousPFBPhase = 0
.InstantaneousPFYPhase = 1
.MeterApparentEnergy = 1.01
.MeterApparentUnit = ApparentEnergyUnit.KiloVoltAmpereHour
.MeterReactiveLagEnergy = 1.25
.MeterReactiveLagError = 1.25
.MeterReactiveLagUnit = ReactiveEnergyUnit.KiloVoltAmpereReactiveHour
.MeterReactiveLeadEnergy = 1.45
.MeterReactiveLeadError = 1.56
.MeterReactiveLeadUnit = ReactiveEnergyUnit.KiloVoltAmpereReactiveHour
.PercentageLoad = 1
.PTRatio = 1
.ReactiveCurrentBPhase = 10
.ReactiveCurrentYPhase = 11
.VoltageBPhase = 10
.VoltageYPhase = 10
End With
testData_List1.accuchek3TestParameters = accuchek3TestParameters1
testData.Add(testData_List1)
Can somebody please guide me?
Your first line is:
Dim testData As List(Of TestData) = Nothing
Then at the bottom you do
testData.Add(testData_List1)
I can't see anywhere in between where you do something like:
testData = New List(Of TestData)()
Though it's slightly hard to read since you've got both a variables and types with TestData as their name (or part of their name) so I might just be missing that.