System.indexoutofrangeexception: index was outside the bounds of the array. visual basic

Forums > Unity Community Discussion > Scripting >

Discussion in 'Scripting' started by glgamesforfun, May 6, 2021.

  • csharp
  • debugging
  • script errors
  • visual studio

(You must log in or sign up to reply here.)

ok, tq but I still stuck
here is the whole code of the program. hope you're willing to check it.

0

'--frmNearestMicLocation----------------------------------------------------------------------------------- ' Calculate the nearest distance for ' microsensor locations ' 'Form variables declared ' 'Command Buttons ' cmdBrowseFolder Browse to select the working directory ' cmdStart Test code with default base or start processing multiple points ' cmdExit End program ' cmdStats Display the form of frmDisplaySensorHisto 'Textboxes ' txtEasting Eastings of point ' txtNorthing Northings of point ' txtFilename Shows directory selected with default input filename ' txtRangeDist Range distance 'Listboxes ' lboNearestStation Show the list of nearest station 'Dialogs ' dlgOpenFile Dialog to browse for the microsensors information file 'Dates ' txtStartingDate Allows users to choose the starting date ' txtEndingDate Allows users to choose the ending date Option Explicit On Option Strict On Public Class frmNearestMicLocation '====CONSTANTS======================= Const dtmEARLYDATE As DateTime = #1/1/1970# Const strDEFAULTFILE As String = "\ibuttons_locations.csv" Const strENDFILE As String = ".csv" Const dblTEST_E As Double = 312773 Const dblTEST_N As Double = 8027373 'Temperature/Humidity Structure Public Structure MicrosensorStatsStruct Dim dblTemp As Double 'Temperature of the data Dim dblHumi As Double 'Humidity of the data Dim dblMaxTemp, dblMinTemp As Double 'Max and min temperature set by users Dim dblMaxHumi, dblMinHumi As Double 'Max and min humidity set by users Dim dblMean As Double 'Mean of the value set by users Dim dteDate As Date 'The date updates Dim dteStartingDate As Date 'The starting data update Dim dteEndingDate As Date 'The ending data update End Structure 'Microsensors Structure Public Structure MicrosensorStruct Dim lngID As Long 'The ID's number of the station Dim strOUTCORP As String 'The OUTCORP for each station Dim strCode As String 'The code of the ID Dim dblNorthing As Double 'Northing coordinate of the data Dim dblEasting As Double 'Esting coordinate of the data Dim dblRngeDist As Double 'Range of distance Dim dteStart As Date 'Starting date Dim dteEnd As Date 'Ending date End Structure '------------------------------------ ' Select file with coordinates of microsensor locations ' ' INPUTS: VB defaults ' OUTPUT: none Private Sub cmdBrowseFolder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdBrowseFolder.Click If dlgFolderBrowser.ShowDialog() = DialogResult.OK Then txtFilename.Text = dlgFolderBrowser.SelectedPath & strDEFAULTFILE End If End Sub '------------------------------------ ' Set up form with initial values ' ' INPUTS: VB defaults ' OUTPUT: none Private Sub frmNearestMicStation_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim dblTEST_E As Double ' Dim dblTEST_N As Double ' 'set up form txtEasting.Text = CStr(dblTEST_E) txtNorthing.Text = CStr(dblTEST_N) txtEasting.Text = "312773" txtNorthing.Text = "8027373" dlgOpenFile.FileName = "" End Sub '------------------------------------ 'Start processing when cmdStart button is clicked ' ' INPUTS: VB defaults ' OUTPUT: none Private Sub cmdStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdStart.Click Dim arrMicrosensor() As MicrosensorStruct Dim arrMicrosensorData() As MicrosensorStatsStruct Dim intNum As Integer Dim strNearestSensor As String Dim strENDFILE As String Dim strFileName As String Dim arrTempHumi(,) As Double Dim intIndex As Integer Dim strSeriesName As String = CStr(1) If txtNrSensor.Text = "" Then MessageBox.Show("Fill in the number of sensors!") ElseIf txtNorthing.Text = "" Then MessageBox.Show("You haven't filled the Northing coordinate!") ElseIf txtEasting.Text = "" Then MessageBox.Show("You haven't filled the Easting coordinate!") ElseIf txtRangeDist.Text = "" Then MessageBox.Show("You haven't filled the range of distance!") Else arrMicrosensor = sensorWithinRange() intNum = CInt(txtNrSensor.Text) For intNum = 0 To intNum - 1 strNearestSensor = dlgFolderBrowser.SelectedPath & "\" & arrMicrosensor(intNum).strCode & strENDFILE strFileName = strNearestSensor & strENDFILE arrMicrosensorData = getSensorRecords(strNearestSensor) intIndex = frmDisplaySensorHisto.chrtMicroData.Series.IndexOf(strSeriesName) 'Add missing series, if it is missing If intIndex < 0 Then frmDisplaySensorHisto.chrtMicroData.Series.Add(strSeriesName) intIndex = frmDisplaySensorHisto.chrtMicroData.Series.IndexOf(strSeriesName) 'Add data For intI = 0 To arrMicrosensorData.GetUpperBound(0) frmDisplaySensorHisto.chrtMicroData.Series.Item(intIndex).Points.AddXY(arrMicrosensorData(intI).dteDate, arrMicrosensorData(intI).dblTemp) Next intI End If 'Call the calculate statistics CalculateStatistics(strFileName, arrTempHumi, arrMicrosensorData) 'Display result in combo box frmDisplaySensorHisto.cboSelectSensor.Items.Add(arrMicrosensor(intNum).strCode) 'List box text frmDisplaySensorHisto.lboSensorID.Items.Add("STATION ID: " & arrMicrosensor(intNum).lngID.ToString & " , " & "REFERENCE CODE: " & arrMicrosensor(intNum).strCode & " , NORTHING: " & arrMicrosensor(intNum).dblNorthing.ToString("F") & " , EASTING: " & arrMicrosensor(intNum).dblEasting.ToString("F") & " , at: " & arrMicrosensor(intNum).dblRngeDist.ToString("F") & "m") frmDisplaySensorHisto.Show() Next intNum End If End Sub '---CalculateDistance--------------------- 'Calculates the distance between a base and a point with projected coordinates 'INPUTS: ' dblBaseN, dblBaseE (double) Base coordinates ' dblLocationN, dblLocationE (double) Point coordinates 'OUTPUT: (double), distance between the two points, -9999.9999 is the default Public Function CalculateDistance(ByVal dblBaseN As Double, ByVal dblBaseE As Double, _ ByVal dblLocationN As Double, ByVal dblLocationE As Double) As Double Dim dblDist As Double 'straight-line distance between points Dim dblDeltaE, dblDeltaN As Double 'differences in easting and northing dblDeltaE = dblBaseE - dblLocationE dblDeltaN = dblBaseN - dblLocationN dblDist = Math.Sqrt(dblDeltaE ^ 2 + Math.Pow(dblDeltaN, 2)) Return (dblDist) End Function '---CalculateBearing---------------------- 'Calculates the bearing between a base and a point with projected coordinates 'INPUTS: ' dblBaseN, dblBaseE (double) Base coordinates ' dblLocationN, dblLocationE (double) Point coordinates 'OUTPUT: (double), bearing of the line connecting the base with the point, -9999.9999 is the default Public Function CalculateBearing(ByVal dblBaseN As Double, ByVal dblBaseE As Double, _ ByVal dblLocationN As Double, ByVal dblLocationE As Double) As Double Dim dblDeltaE, dblDeltaN As Double 'differences in easting and northing Dim dblAngle As Double 'bearing uncorrected for quadrant Dim dblBearing As Double 'bearing from base to station 'differences between base & station dblAngle = 0.0 dblDeltaE = dblBaseE - dblLocationE dblDeltaN = dblBaseN - dblLocationN 'avoid division by zero If dblDeltaN = 0 Then If (dblDeltaE < 0) Then dblBearing = 90 'directly east Else dblBearing = 270 'directly west End If Else dblAngle = Math.Atan(Math.Abs(dblDeltaE) / Math.Abs(dblDeltaN)) dblAngle = dblAngle * 180.0 / Math.PI 'convert to degrees 'adjust for quadrant If (dblDeltaE <= 0 And dblDeltaN < 0) Then 'Quadrant I dblBearing = dblAngle ElseIf (dblDeltaE <= 0 And dblDeltaN > 0) Then 'Quadrant II dblBearing = 180 - dblAngle ElseIf (dblDeltaE > 0 And dblDeltaN > 0) Then 'Quadrant III dblBearing = 180 + dblAngle Else 'Quadrant IV dblBearing = 360 - dblAngle End If End If Return (dblBearing) End Function '--- SensorWithinRange -------------------------------- 'Get the record from files and display it on the listbox 'INPUTS: ' VB Defaults 'OUTPUT: ' 2-D Arrays Public Function sensorWithinRange() As MicrosensorStruct() Dim arrMicrosensor() As MicrosensorStruct ' Dim dblNearestStation As MicrosensorStruct ' Dim intStationCounter As Integer 'Counter for stations Dim dblStationE As Double 'Easting coords of one station Dim dblStationN As Double 'Northing coords of one station Dim intNearestSensor As Integer ' Dim strNearestSensor() As String ' Dim intA, intB, IntMaxIndex As Integer ' Dim dblMaxValue As Double ' Dim sMax, sTemp As MicrosensorStruct ' Dim strTextOut As String ' Dim strArrColumns() As String 'Columns within 1 station record Dim chrArrDelim() As Char = " ,".ToCharArray() 'File delimiter Dim sReader As IO.StreamReader Dim strRecord As String intStationCounter = -1 intNearestSensor = 0 dblStationE = CDbl(txtEasting.Text) dblStationN = CDbl(txtNorthing.Text) sReader = IO.File.OpenText(txtFilename.Text) strRecord = sReader.ReadLine() strRecord = sReader.ReadLine() Do While (Not sReader.EndOfStream) strRecord = sReader.ReadLine() intStationCounter = (intStationCounter + 1) Loop sReader.Close() Dim intNrStations As Integer 'Total number of station ReDim arrMicrosensor(intNrStations) sReader = IO.File.OpenText(txtFilename.Text) strRecord = sReader.ReadLine() dblNearestStation.dblRngeDist = Double.PositiveInfinity For intStationCounter = 0 To intNrStations - 1 strRecord = sReader.ReadLine() strArrColumns = strRecord.Split(chrArrDelim) arrMicrosensor(intStationCounter).lngID = CLng(strArrColumns(0)) arrMicrosensor(intStationCounter).strOUTCORP = strArrColumns(1) arrMicrosensor(intStationCounter).strCode = strArrColumns(2) arrMicrosensor(intStationCounter).dblNorthing = CDbl(strArrColumns(3)) arrMicrosensor(intStationCounter).dblEasting = CDbl(strArrColumns(4)) arrMicrosensor(intStationCounter).dblRngeDist = CalculateDistance(dblStationN, dblStationE, arrMicrosensor(intStationCounter).dblNorthing, arrMicrosensor(intStationCounter).dblEasting) If arrMicrosensor(intStationCounter).dblRngeDist < CDbl(txtRangeDist.Text) Then intNearestSensor = intNearestSensor + 1 'string for text in listbox lboNearestStation.Items.Add("STATION ID:" & arrMicrosensor(intStationCounter).lngID.ToString & " , " _ & "REFERENCE CODE:" & arrMicrosensor(intStationCounter).strCode & " , NORTHING:" _ & arrMicrosensor(intStationCounter).dblNorthing.ToString("F") & ", EASTING:" _ & arrMicrosensor(intStationCounter).dblEasting.ToString("F") & ", at:" _ & arrMicrosensor(intStationCounter).dblRngeDist.ToString("F") & "m") End If Next intStationCounter sReader.Close() ReDim strNearestSensor(intNearestSensor - 1) For intStationCounter = 0 To intNrStations - 1 If arrMicrosensor(intStationCounter).dblRngeDist < CDbl(txtRangeDist.Text) Then intNearestSensor = 0 strNearestSensor(intNearestSensor) = arrMicrosensor(intStationCounter).strCode End If Next Dim intNum As Integer intNum = CInt(txtNrSensor.Text) For intNum = 0 To intNum - 1 For intA = arrMicrosensor.GetUpperBound(0) To 1 Step -1 sMax = arrMicrosensor(0) dblMaxValue = sMax.dblRngeDist IntMaxIndex = 0 For intB = 0 To intA If arrMicrosensor(intB).dblRngeDist > dblMaxValue Then dblMaxValue = arrMicrosensor(intB).dblRngeDist IntMaxIndex = intB End If Next intB sTemp = arrMicrosensor(intA) arrMicrosensor(intA) = arrMicrosensor(IntMaxIndex) arrMicrosensor(IntMaxIndex) = sTemp Next intA strTextOut = arrMicrosensor(intNum).strCode Next intNum Return arrMicrosensor End Function '---GetSensorRecords----------------------------------------- ' will show us the nearby station of selected point 'INPUTS: ' VB defaults 'OUTPUT: ' The list of nearby station Public Function getSensorRecords(ByVal strFileName As String) As MicrosensorStatsStruct() Dim arrMicrosensorData() As MicrosensorStatsStruct ' Dim intNrStations As Integer ' Dim intCounter As Integer ' Dim strTextOut As String ' Dim strRecords As String ' Dim dblSensorTemp As Double ' Dim dblSensorHumi As Double ' Dim sReader As IO.StreamReader ' Dim dtmDte As Date ' Dim strArrColumns() As String ' Dim chrArrDelim() As Char = ", ".ToCharArray() ' 'Get the array size ReDim arrMicrosensorData(intNrStations - 1) Try 'Open stream sReader = IO.File.OpenText(strFileName) 'Find the total lines number in the file intNrStations = 0 Do Until sReader.EndOfStream strRecords = sReader.ReadLine() If strRecords <> "" Then intNrStations = intNrStations + 1 End If Loop intNrStations = intNrStations - 1 sReader.Close() ReDim arrMicrosensorData(intNrStations - 1) 'Save the values into the array sReader = IO.File.OpenText(strFileName) strRecords = sReader.ReadLine() For intNrStations = 0 To intNrStations - 1 strRecords = sReader.ReadLine() 'arrMicrosensorData = GetValuesFromString(strRecords) strArrColumns = strRecords.Split(chrArrDelim) dtmDte = CDate(strArrColumns(0)) arrMicrosensorData(intCounter).dteDate = dtmDte dblSensorTemp = CDbl(strArrColumns(1)) arrMicrosensorData(intCounter).dblTemp = dblSensorTemp dblSensorHumi = CDbl(strArrColumns(2)) arrMicrosensorData(intCounter).dblHumi = dblSensorHumi strTextOut = "Date Time: " & arrMicrosensorData(intCounter).dteDate.ToString & " Temperature: " & CStr(arrMicrosensorData(intCounter).dblTemp).ToString & ("°C") & " , Humidity: " & ("%") lboMicrosensorData.Items.Add(strTextOut) Next intNrStations sReader.Close() Catch noFileErr As IO.FileNotFoundException MessageBox.Show("Check your file!") Catch ioErr As IO.IOException MessageBox.Show("File not found!") Catch exNull As ArgumentException MessageBox.Show("Invalid argument!") arrMicrosensorData = Nothing End Try Return arrMicrosensorData End Function 'Converts a comma-delimited String of Sensor data 'into MeteodataStruct type 'INPUT: strRecord (String(,)) - Sensor records 'OUTPUT: (MeteodataStruct()) - Sensor records '===================================================================================== Public Function GetValuesFromString(ByVal strRecord As String, ByRef Microsensordata As MicrosensorStatsStruct) As MicrosensorStatsStruct Dim chrArrDelim() As Char = ",".ToCharArray() 'delimiter Dim strArrColumns() As String 'columns within record 'add error traps Microsensordata.dteDate = Nothing Microsensordata.dblTemp = -9999999 Microsensordata.dblHumi = -9999999 Try 'split record strArrColumns = strRecord.Split(chrArrDelim) 'convert types and save Microsensordata.dteDate = GetDateFromString(strArrColumns(0)) Microsensordata.dblTemp = CDbl(strArrColumns(1)) Microsensordata.dblHumi = CDbl(strArrColumns(2)) Catch errInput As InvalidCastException MessageBox.Show("Check the input!") End Try Return Microsensordata End Function 'Converts a string (in format dd/mm/yyyy) 'into a date object. 'If format is invalid, returns Nothing 'REF: E-K Gulland 1 May 2012 'INPUT: strDate (String) - date as text dd/mm/yyyy 'OUTPUT: (DateTime) - date object '=========================================================================== Private Function GetDateFromString(ByVal strDate As String) As DateTime Dim dteDate As DateTime = Nothing ' Dim chrArrDelim() As Char = "/".ToCharArray() 'delimiter Dim strArrColumns() As String 'columns within record Dim intDay, intMonth, intYear As Integer 'components of date Try strArrColumns = strDate.Split(chrArrDelim) intDay = CInt(strArrColumns(0)) intMonth = CInt(strArrColumns(1)) intYear = CInt(strArrColumns(2)) dteDate = New DateTime(intYear, intMonth, intDay) Catch castErr As InvalidCastException dteDate = Nothing 'invalid date format Catch indexErr As IndexOutOfRangeException dteDate = Nothing 'missing component or didn't use "/" Catch dateErr As ArgumentOutOfRangeException dteDate = Nothing 'day, month or year invalid End Try Return dteDate End Function 'Title: Subroutine CalculateStatistics 'Calculates the Min and Max values for a selected statistics for a selected sensor 'INPUTS ' lngSensorID ID of the selected sensor ' Statistics The desired statistics 'OUTPUT ' Min and Max values '==================================================================================== Public Function CalculateStatistics(ByVal strFileName As String, ByRef arrTempHumi(,) As Double, ByRef arrMicrosensorData() As MicrosensorStatsStruct) As Double(,) Dim dblMinTemp As Double ' Dim dblMaxTemp As Double ' Dim dblMinHumi As Double ' Dim dblMaxHumi As Double ' Dim dteStartingDate As Date ' Dim dteEndingDate As Date ' Dim strTextOut As String ' ReDim arrTempHumi(0, 3) 'initialize dblMaxTemp = Double.NegativeInfinity dblMinTemp = Double.PositiveInfinity dblMaxHumi = Double.NegativeInfinity dblMinHumi = Double.PositiveInfinity dteStartingDate = dtpStartingDate.Value dteEndingDate = dtpEndingDate.Value Try If arrMicrosensorData IsNot Nothing Then For intI = 0 To arrMicrosensorData.GetUpperBound(0) If ((arrMicrosensorData(intI).dteDate >= dteStartingDate) And (arrMicrosensorData(intI).dteDate <= dteEndingDate)) Then If arrMicrosensorData(intI).dblTemp > dblMaxTemp Then dblMaxTemp = arrMicrosensorData(intI).dblTemp End If If arrMicrosensorData(intI).dblTemp < dblMinTemp Then dblMinTemp = arrMicrosensorData(intI).dblTemp End If If arrMicrosensorData(intI).dblHumi > dblMaxHumi Then dblMaxHumi = arrMicrosensorData(intI).dblHumi End If If arrMicrosensorData(intI).dblHumi > dblMinHumi Then dblMinHumi = arrMicrosensorData(intI).dblHumi End If End If Next intI End If Catch exNull As NullReferenceException MessageBox.Show("Bad file Format") End Try arrTempHumi(0, 0) = dblMaxTemp arrTempHumi(0, 1) = dblMinTemp arrTempHumi(0, 2) = dblMaxHumi arrTempHumi(0, 3) = dblMinHumi strTextOut = "MaxTemp: " & arrTempHumi(0, 0).ToString & "(°C)" & "," & "MinTemp: " & arrTempHumi(0, 1).ToString & "(°C)" & "," & "MaxHumi: " & arrTempHumi(0, 2).ToString & "," & "MinHumi" & arrTempHumi(0, 3).ToString frmDisplaySensorHisto.lboStats.Items.Add(strTextOut) Return arrTempHumi End Function Private Sub cmdExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdExit.Click Me.Close() End Sub End Class