I am trying to use Public variables and my variables are Empty when I need them. Here's what I am doing. I have a database app that tracks happenings during a submersible dive. There are several forms that track things like launch of vehicle, vehicle on bottom, start a transect, take a picture, enter an observation, take a sample, leave bottom, etc. There are several nested forms with vba code controlling what happens. One of the things that is done over and over is reading a log with the current lat/lon and depth of the submersible. In some cases, that log may not be available and the user has to enter the lat/lon themselves in a popup form called "LatLonDataEntry". They can enter the lat/lon in any format (decimal degrees, degrees and decimal minutes, or degrees minutes and decimal seconds) and the code will convert it to decimal degrees (ex. 30.2345 and -88.1234), which is the preferred format. I have set variables for LatDecDeg and LonDecDeg to public so that after they are calculated in the LatLonDataEntry form, they can be used when I come back from that form. This happens in several places in the application where it is needed. I had read that I couldn't declare public variables in Form modules, so I'm declaring them in a module that also contains an often used function.
Private Sub SetLaunchTimeNow_Click()
' Launch Now button should make a new dive note record and put in the phrase "launch" and put in the current date/time, lat/lon from the user entry form.
Dim nowtime As String
DoCmd.OpenForm "LatLonDataEntry", acNormal, "", "", , acDialog
'set the time, date/time, lat, lon, and depth in the splash note
nowtime = Now()
Me!Time_Launch = Format(nowtime, "hh:nn:ss")
Me!Date_Time_Launch = nowtime
Me!Latitude_SITE = DecDegLat
Me!Longitude_SITE = DecDegLon
'move the focus to the dive note subform
Form_frm_tbl_DiveNote.Form![Date_Time_Notes].SetFocus
'add a new dive note record and then set all of the variables to the same lat, lon, and depth that you added to the splash note
'add the note "Launch" to the Habitat Description
Form_frm_tbl_DiveNote.Recordset.AddNew
Debug.Print "Added a new Record for Launch"
Form_frm_tbl_DiveNote!SplashID = Me!SplashID
Form_frm_tbl_DiveNote!ExtraNote_ID = Form_frm_tbl_DiveNote!DiveNote_ID
Form_frm_tbl_DiveNote!Date_Time_Notes = nowtime
Form_frm_tbl_DiveNote!Event = "Launch"
Form_frm_tbl_DiveNote!Latitude = DecDegLat
Form_frm_tbl_DiveNote!Longitude = DecDegLon
Form_frm_tbl_DiveNote!HabitatDescription.SetFocus
End Sub
The module which has the public variable declarations and the function that is called when the log is available is:
Option Explicit
Public db As Database
Public puttylog As Recordset
Public rst As Recordset
Public spl As Recordset
Public currcruise As String
Public currlat As String
Public currlon As String
Public currdepth As String
Public DecDegLat As String
Public DecDegLon As String
Public lasttransect As Integer
Public transectstarted As Boolean
Public NSHemisphere As String
Public EWHemisphere As String
Public Function RetLatLonDepth()
Set db = CurrentDb()
Set puttylog = db.OpenRecordset("Putty_log")
'move the first record (only record) and read in the current lat, lon, and depth
puttylog.MoveFirst
currlat = Str(puttylog![lat_GPRMC])
currlon = Str(Format(puttylog![lon_GPRMC], "00000.0000"))
currdepth = Trim(puttylog!Depth)
' reset the recordset and database to nothing to release it
Set puttylog = Nothing
Set db = Nothing
End Function
The code behind the LatLonDataEntry popup window used to read the lat/lon values is:
Option Explicit
Dim lat As Integer
Dim lon As Integer
Dim min As Integer
Dim latmin As Single
Dim lonmin As Single
Dim DecDeg As Single
Dim decmin As Single
Dim minsec As Single
Dim decsec As Single
Dim numspaces As Integer
Public Sub LatInput_AfterUpdate()
If IsNumeric(LatInput) = True Then
' the latitude was entered in dec degrees
If LatInput > 90 Or LatInput < -90 Then
GoTo LatError
Else
LatInput = Fix(LatInput * 100000) / 100000
If LatInput < 0 Then
NSHemisphere = "Southern Hemisphere"
Else
NSHemisphere = "Northern Hemisphere"
End If
End If
LatDecDeg = Str(LatInput)
lat = Fix(LatInput)
latmin = Round(Abs(LatInput) - Abs(lat), 5)
decmin = latmin * 60
LatDegDecMin = Format(Str(lat), "00") & " " & Str(latmin * 60)
min = Fix(decmin)
minsec = Round(Abs(decmin) - Abs(min), 6)
LatDegMinDecSec = Format(Str(lat), "00") & " " & Format(Str(min), "00") & Str(minsec * 60)
Debug.Print LatDegMinDecSec
Else
numspaces = Len(LatInput) - Len(Replace(LatInput, " ", ""))
If (numspaces = 1) Then
' the latitude was entered in deg dec min
LatDegDecMin = Str(LatInput)
lat = Int(Split(LatInput, " ")(0))
decmin = CDbl(Split(LatInput, " ")(1))
LatDecDeg = Format((lat + decmin / 60), "00.00000")
min = Fix(decmin)
minsec = Round(Abs(decmin) - Abs(min), 5)
LatDegMinDecSec = Format(Str(lat), "00") & " " & Format(Str(min), "00") & Str(minsec * 60)
Else
If (numspaces = 2) Then
' the latitude was entered in deg min dec sec
LatDegMinDecSec = Str(LatInput)
lat = Int(Split(LatInput, " ")(0))
min = Int(Split(LatInput, " ")(1))
decsec = CDbl(Split(LatInput, " ")(2))
decmin = min + decsec / 60
DecDeg = lat + decmin / 60
LatDecDeg = Format(Str(DecDeg), "00.00000")
LatDegDecMin = Format(Str(lat), "00") & " " & Format(Str(decmin), "00.00000")
Else
LatError:
MsgBox ("You have entered an invalid format for Latitude or a value that is out of range (-90 to 90).")
End If
End If
End If
End Sub
Public Sub LatLonOK_Click()
DecDegLat = LatDecDeg
DecDegLon = LonDecDeg
End Sub
Public Sub LonInput_AfterUpdate()
If IsNumeric(LonInput) = True Then
' the Longitude was entered in dec degrees
If LonInput > 180 Or LonInput < -180 Then
GoTo LonError
Else
LonInput = Fix(LonInput * 100000) / 100000
If LonInput < 0 Then
EWHemisphere = "Western Hemisphere"
Else
EWHemisphere = "Eastern Hemisphere"
End If
End If
LonDecDeg = Str(LonInput)
lon = Fix(LonInput)
lonmin = Round(Abs(LonInput) - Abs(lon), 6)
decmin = lonmin * 60
LonDegDecMin = Format(Str(lon), "000") & " " & Str(lonmin * 60)
min = Fix(decmin)
minsec = Round(Abs(decmin) - Abs(min), 6)
LonDegMinDecSec = Format(Str(lon), "000") & " " & Format(Str(min), "000") & Str(minsec * 60)
Else
numspaces = Len(LonInput) - Len(Replace(LonInput, " ", ""))
If (numspaces = 1) Then
' the Longitude was entered in deg dec min
LonDegDecMin = Str(LonInput)
lon = Int(Split(LonInput, " ")(0))
decmin = CDbl(Split(LonInput, " ")(1))
LonDecDeg = Format((lon + decmin / 60), "000.00000")
min = Fix(decmin)
minsec = Round(Abs(decmin) - Abs(min), 6)
LonDegMinDecSec = Format(Str(lon), "000") & " " & Format(Str(min), "00") & Str(minsec * 60)
Else
If (numspaces = 2) Then
' the Longitude was entered in deg min dec sec
LonDegMinDecSec = Str(LonInput)
lon = Int(Split(LonInput, " ")(0))
min = Int(Split(LonInput, " ")(1))
decsec = CDbl(Split(LonInput, " ")(2))
decmin = min + decsec / 60
DecDeg = lon + decmin / 60
LonDecDeg = Format(Str(DecDeg), "000.00000")
LonDegDecMin = Format(Str(lon), "000") & " " & Format(Str(decmin), "00.00000")
Else
LonError:
MsgBox ("You have entered an invalid format for Longitude or a value that is out of range (-180 to 180).")
End If
End If
End If
End Sub
Related
I want to write the values of a sine function to a text file. The function is
In my graphing calculator, I also have to add π if I want to plot the function in radians.
How do I have to write this in the source code? Wrong values come out every time, regardless of whether I insert or leave out π.
I would like to have a y-value of 0 for t = 0 to 14400, and also from t = 69060 onwards. In between, according to its formula, the sine function of y = 0 should rise, reach 8, and fall again (second zero as said at 69060).
Private Sub ButtonStart_Click(sender As Object, e As EventArgs) Handles ButtonStart.Click
Dim Path As String = ""
Using SFD As New CommonSaveFileDialog
SFD.Title = "Ordner, in dem die Textdatei gespeichert werden soll, auswählen"
SFD.Filters.Add(New CommonFileDialogFilter("Textdateien", ".txt"))
Dim di As New IO.DirectoryInfo(Application.StartupPath)
If di.Parent.Name = "bin" Then
di = di.Parent.Parent.Parent ' AnyCPU
ElseIf di.Parent.Parent.Name = "bin" Then
di = di.Parent.Parent.Parent.Parent ' x64, x86
End If
If System.IO.Directory.Exists(di.FullName) Then
SFD.InitialDirectory = di.FullName
Else
SFD.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
End If
If SFD.ShowDialog() = CommonFileDialogResult.Ok Then
Path = SFD.FileName & ".txt"
Else
Return
End If
End Using
ButtonStart.BackColor = Color.FromArgb(255, 255, 0)
Application.DoEvents()
Using textfile As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(Path, False, System.Text.Encoding.UTF8)
textfile.WriteLine($"Time{Tab}V(OUT)")
For t As UInt32 = 0UI To 86400UI Step 1UI
If t < 14400UI OrElse (t >= 14400UI AndAlso t <= 69060UI) Then
textfile.WriteLine(t.ToString(Eng).PadLeft(10, "0"c) & Tab & 0.0.ToString(Eng))
Else
Dim Value As Double = 8.0 * Math.Sin(1.0 * Math.PI / 54660.0 * t + 2.0 * Math.PI - 0.2634467618)
textfile.WriteLine(t.ToString(Eng).PadLeft(10, "0"c) & Tab & Value.ToString(Eng))
End If
Next
textfile.Close()
End Using
ButtonStart.BackColor = Color.FromArgb(0, 255, 0)
End Sub
This should be your function
Function f(t As Double) As Double
Dim amplitude = 8
Dim period = 54660
Dim phaseDegrees = 177
Dim phaseRadians = phaseDegrees * Math.PI / 180
Dim vertical = 0
Dim a = amplitude
Dim b = 2 * Math.PI / period
Dim c = phaseRadians
Dim d = vertical
Return a * Math.Sin(b * (t + c)) + d
End Function
See image, from https://www.mathsisfun.com/algebra/amplitude-period-frequency-phase-shift.html
I found a solution. It has to be
Amplitude * sin(2πf*t + phase in rad) + offset
Using textfile As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(Path, False, System.Text.Encoding.UTF8)
For t As UInt32 = 0UI To 86400UI Step 1UI
If t < 14400UI OrElse (t > 69060UI AndAlso t <= 86400UI) Then
textfile.WriteLine(t.ToString(Eng).PadLeft(10, "0"c) & Tab & 0.0.ToString(Eng))
Else
Dim Value As Double = 4.0 * Math.Sin(2 * Math.PI * 1.0 / 54660.0 * t + 177.0 * Math.PI / 180.0) + 4.0
textfile.WriteLine(t.ToString(Eng).PadLeft(10, "0"c) & Tab & Value.ToString(Eng))
End If
Next
textfile.Close()
End Using
I am running a catscript that imports a txt file and loads .cgr files into catia to generate a 3dxml file. When this 3dxml file is opened all the cgr components are present but the product structure is flat with no multi-level nodes available. I have followed the catia documentation for adding components to generate the code. The aim of this code is to generate a part with its silhouettes(full cgrs). Here is the code:
Sub CATMain()
Dim file_name As String
Dim RootPartNumber As String
Dim linecount As Interger
Dim input_level As Interger
Dim dbinput_file as File
Dim arrFields
Dim dbinput_file_stream As TextStream
Dim iMatrix(12)
Dim oMatrix(11)
Dim mMatrix(2137,12)
Dim repo_path(10000) As String
Dim cgrpath_part(10000,10000) As String
Dim repo_path_present As Integer
Dim index As Integer
Dim Str As String
Dim ProductArray(10000) As Product
Dim FileSysObject
Dim Instance As Product
Dim file_directory As String
Dim file_extension As String
Set FileSysObject = CATIA.FileSystem
flag = false
file_name=CATIA.SystemService.Environ("SIL_INPUTFLE")
file_directory="/tmp/DLNAME4/"
file_extension=".3dxml"
'CATIA.SystemService.print "Input Argument is " & file_name
Dim value as Boolean
value=FileSysObject.FileExists(file_name)
' MsgBox " return value is " & value
If (Not CATIA.FileSystem.FileExists (file_name)) Then
CATIA.SystemService.print "path not found "
End If
Set dbinput_file = FileSysObject.GetFile(file_name)
Set dbinput_file_stream = dbinput_file.OpenAsTextStream("ForReading")
repo_path_present=0
linecount=1
'Create a new product document object by adding a document with the Product
'type to the document collection of the CATIA application.
Dim oProductDoc As Document
Set oProductDoc = CATIA.Documents.Add("Product")
'Retrieve the Design part as the root product.
Dim odesign As Product
Set odesign = oProductDoc.Product
'Retrieve the product's collection of the Design.
Dim odesignProducts As Products
Set odesignProducts = odesign.Products
' Read a line at a time until EOF
Dim linein As String
linein = dbinput_file_stream.ReadLine
Do While Not dbinput_file_stream.AtEndOfStream
' CATIA.SystemService.print " value of linein is " & linein
arrFields = Split(linein,",")
' iMatrix = arrFields
' CATIA.SystemService.print " value of arrFields is " & arrFields
'for each x in arrFields
'For i = Lbound(arrFields) to Ubound(arrFields)
RootPartNumber=arrFields(0)
odesign.PartNumber=RootPartNumber
odesign.Name = RootPartNumber
iMatrix(0) = CDbl(arrFields(1))
iMatrix(1) = CDbl(arrFields(2))
iMatrix(2) = CDbl(arrFields(3))
iMatrix(3) = CDbl(arrFields(4))
iMatrix(4) = CDbl(arrFields(5))
iMatrix(5) = CDbl(arrFields(6))
iMatrix(6) = CDbl(arrFields(7))
iMatrix(7) = CDbl(arrFields(8))
iMatrix(8) = CDbl(arrFields(9))
iMatrix(9) = CDbl(arrFields(10))
iMatrix(10) =CDbl(arrFields(11))
iMatrix(11) =CDbl(arrFields(12))
iMatrix(12) =CDbl(arrFields(13))
' Here we are storing the cgr path is an Array repo_path and if the cgr already exsists in the array its not added then
If linecount=1 then
repo_path(linecount-1)=arrFields(15)
reDim repoList(0)
repoList(0) = arrFields(15)
End If
If linecount >1 then
'CATIA.SystemService.print "looking for " & arrFields(15)
' CATIA.SystemService.print " line_count is " &linecount
For index=0 to linecount-1
If arrFields(15)=repo_path(index) then
repo_path_present=1
'CATIA.SystemService.print " path found with index vlaue " & index
Exit For
Else
'CATIA.SystemService.print " else "
If linecount-1-index=1 then
'CATIA.SystemService.print " new cgr with kvlaue " & index
repo_path_present=0
repo_path(index+1)=arrFields(15)
' CATIA.SystemService.print " new cgr with n pos " & index+1
Exit For
Else
' CATIA.SystemService.print " e1"
End If
End if
Next
End if
flag = false
input_level=iMatrix(0)
If input_level=1 Then
For j = 1 to Ubound(iMatrix)
mMatrix(input_level,j)=iMatrix(j)
Next
Else
mMatrix(input_level,1) = (mMatrix(input_level-1,1) * iMatrix(1)) + (mMatrix(input_level-1,4) * iMatrix(2)) + (mMatrix(input_level-1,7) * iMatrix(3))
mMatrix(input_level,2) = (mMatrix(input_level-1,2) * iMatrix(1)) + (mMatrix(input_level-1,5) * iMatrix(2)) + (mMatrix(input_level-1,8) * iMatrix(3))
mMatrix(input_level,3) = (mMatrix(input_level-1,3) * iMatrix(1)) + (mMatrix(input_level-1,6) * iMatrix(2)) + (mMatrix(input_level-1,9) * iMatrix(3))
mMatrix(input_level,4) = (mMatrix(input_level-1,1) * iMatrix(4)) + (mMatrix(input_level-1,4) * iMatrix(5)) + (mMatrix(input_level-1,7) * iMatrix(6))
mMatrix(input_level,5) = (mMatrix(input_level-1,2) * iMatrix(4)) + (mMatrix(input_level-1,5) * iMatrix(5)) + (mMatrix(input_level-1,8) * iMatrix(6))
mMatrix(input_level,6) = (mMatrix(input_level-1,3) * iMatrix(4)) + (mMatrix(input_level-1,6) * iMatrix(5)) + (mMatrix(input_level-1,9) * iMatrix(6))
mMatrix(input_level,7) = (mMatrix(input_level-1,1) * iMatrix(7)) + (mMatrix(input_level-1,4) * iMatrix(8)) + (mMatrix(input_level-1,7) * iMatrix(9))
mMatrix(input_level,8) = (mMatrix(input_level-1,2) * iMatrix(7)) + (mMatrix(input_level-1,5) * iMatrix(8)) + (mMatrix(input_level-1,8) * iMatrix(9))
mMatrix(input_level,9) = (mMatrix(input_level-1,3) * iMatrix(7)) + (mMatrix(input_level-1,6) * iMatrix(8)) + (mMatrix(input_level-1,9) * iMatrix(9))
mMatrix(input_level,10) =(mMatrix(input_level-1,1) * iMatrix(10)) + (mMatrix(input_level-1,4) * iMatrix(11)) + (mMatrix(input_level-1,7) * iMatrix(12) + mMatrix(input_level-1,10))
mMatrix(input_level,11) =(mMatrix(input_level-1,2) * iMatrix(10)) + (mMatrix(input_level-1,5) * iMatrix(11)) + (mMatrix(input_level-1,8) * iMatrix(12) + mMatrix(input_level-1,11))
mMatrix(input_level,12) =(mMatrix(input_level-1,3) * iMatrix(10)) + (mMatrix(input_level-1,6) * iMatrix(11)) + (mMatrix(input_level-1,9) * iMatrix(12) + mMatrix(input_level-1,12))
End If
' MsgBox " value of linecount is " & linecount
' linecount = linecount + 1
for j = 1 to 12
oMatrix(j-1) = mMatrix(input_level,j)
Next
' If repo_path_present value is set to 0 then the current entry is a new product
If repo_path_present=0 then
' CATIA.SystemService.print " New product "
Dim oSIL_Prod As Product
If InStr(arrFields(14), "/") <> 0 Then
arrFields(14)=Replace(arrFields(14),"/","-")
End if
Set oSIL_Prod = odesignProducts.AddNewProduct(arrFields(14))
oSIL_Prod.PartNumber = arrFields(14)
oSIL_Prod.Name = linecount
'Add a master shape representation to the hull using an existing part and
'reframe the viewer.
oSIL_Prod.AddMasterShapeRepresentation arrFields(15)
' CATIA.ActiveWindow.ActiveViewer.Reframe
oSIL_Prod.Move.Apply oMatrix
End If
'Copy the product reference is a array ProductArray
Set ProductArray(linecount-1)=oSIL_Prod.ReferenceProduct
' If repo_path_present value is set to 1 then the current entry is already present. Use Add component
If repo_path_present=1 then
' CATIA.SystemService.print " New component "
'CATIA.SystemService.print " found with index vlaue " & index
Set Instance= ProductArray(index)
'Dim ProductInstance As Product
Set ProductInstance = odesignProducts.AddComponent(Instance)
ProductInstance.Name = linecount
ProductInstance.Move.Apply oMatrix
'CATIA.SystemService.print " ProductArray value is " & ProductArray(linecount-1)
End If
linecount= linecount + 1
linein = dbinput_file_stream.ReadLine
Loop
' Close file
dbinput_file_stream.Close
'Save as 3dxml file
'oProductDoc.SaveAs file_directory & odesign.PartNumber & file_extension
oProductDoc.ExportData file_directory & odesign.PartNumber , "3dxml"
End Sub
When the 3dxml file is opened it should not have a flat structure but instead have indented nodes.
My calculations work but every time I run the program my output will be the "negative, does not exceed" result. I'm very new to all this so please any suggestions will help.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim foodname As String = MaskedTextBox1.Text
Dim calories As Integer = MaskedTextBox2.Text
Dim fat As Integer = MaskedTextBox3.Text
Dim calculation As Double = (fat * 9) / calories
Dim positive As String = "which exceeds AHA recommendation"
Dim negative As String = "which does not exceed AHA recommendation"
ListBox1.Items.Clear()
If ((fat * 9) / calories) > (0.3 * 100) Then
ListBox1.Items.Add(foodname & " contains " & FormatPercent(calculation) & " calories from fat, " & positive)
ElseIf ((fat * 9) / calories) < (0.29 * 100) Then
ListBox1.Items.Add(foodname & " contains " & FormatPercent(calculation) & " calories from fat, " & negative)
End If
End Sub
End Class
would this help?
If ((fat * 9) / calories) > (0.3 * 100) Then
ListBox1.Items.Add(foodname & " contains " & FormatPercent(calculation) & " calories from fat, " & positive)
Else
ListBox1.Items.Add(foodname & " contains " & FormatPercent(calculation) & " calories from fat, " & negative)
End If
you have only two options here, no need for 2 conditions. either the first one is true, or it must be the second one
At the start of the program I define a new Public Structure 'Data':
Public Structure Data
Dim car, grid, points As String
Dim driver, team, fastestlap, racetime As String
End Structure
I then have the user input data and it is added to array displayData(5) of data type 'Data'.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim displayData(5) As Data
Dim accepted As Boolean = False
Dim temp As String
Dim tempNum As Integer
Dim output As String = ""
Dim arraysize As Integer = 0
For x = 0 To 5
displayData(x).driver = InputBox("Please enter the name of driver number " & x + 1)
temp = InputBox("Please enter the car number of driver number " & x + 1)
While accepted = False
If IsNumeric(temp) Then
accepted = True
displayData(x).car = temp
Else
accepted = False
temp = InputBox("Error: integer not entered. Please enter the car number of driver number " & x + 1)
End If
End While
accepted = False
displayData(x).team = InputBox("Please enter the team name of driver number " & x + 1)
temp = InputBox("Please enter the grid number of driver number " & x + 1)
tempNum = Convert.ToInt32(temp)
While accepted = False
If IsNumeric(tempNum) Then
accepted = True
displayData(x).grid = temp
Else
accepted = False
temp = InputBox("Error: integer not entered. Please enter the grid number of driver number " & x + 1)
tempNum = Convert.ToInt32(temp)
End If
End While
accepted = False
displayData(x).fastestlap = InputBox("Please enter the fastest lap of driver number " & x + 1)
displayData(x).racetime = InputBox("Please enter the race time of driver number " & x + 1)
temp = InputBox("Please enter the points of driver number " & x + 1)
While accepted = False
If IsNumeric(temp) Then
accepted = True
displayData(x).points = temp
Else
accepted = False
temp = InputBox("Error: integer not entered. Please enter the points of driver number " & x + 1)
End If
End While
accepted = False
output = output & displayData(x).driver & "," & displayData(x).car & "," & displayData(x).team & "," & displayData(x).grid & "," & displayData(x).fastestlap & "," & displayData(x).racetime & "," & displayData(x).points & vbCrLf
Next
Dim filename As String = "U:\Subjects\Computing\AH Computing\Project Files\Leaderboard.csv"
My.Computer.FileSystem.WriteAllText(filename, output, True)
bubbleSort(arraysize, displayData(6))
End Sub
Above is the main bulk of my code. I am getting an error from typing in displayData(6) into bubblesort, which is defined here:
Public Sub bubbleSort(ByVal arraysize As Integer, ByVal displayData() As Data)
Dim counter As Integer
Dim outerloop As Integer
For outerloop = (arraysize - 2) To 0 Step -1
For counter = 0 To outerloop
If displayData(counter).racetime > displayData(counter + 1).racetime Then
swap(displayData(counter).racetime, displayData(counter + 1).racetime)
swap(displayData(counter).car, displayData(counter + 1).car)
swap(displayData(counter).driver, displayData(counter + 1).driver)
swap(displayData(counter).points, displayData(counter + 1).points)
swap(displayData(counter).team, displayData(counter + 1).team)
swap(displayData(counter).fastestlap, displayData(counter + 1).fastestlap)
swap(displayData(counter).grid, displayData(counter + 1).grid)
End If
Next
Next
End Sub
And apparently I need more normal text in order to save this. The bubble sort uses a swap algorithm that I defined in another part of the program, but it is incredibly simple and is 100% not the cause of the error so it seems unproductive to include it.
I have expression string:
dim str as string = "999999999 * 999999999"
I use DataTable.Compute to calculate:
dim dt as new datatable
dim result as double = 0
result = cdbl(dt.Compute(str))
And I get an error:
Value is either too large or too small for Type 'Int32'.
How can I control result datatype in this case?
Solution:
This function work like Windows's Calculator. Code so confuse but it work :)
'input = "999,999,999 x 888,888,888 + 112,365 ÷ 15 − 987,653"
Public Shared Function strCalc(ByVal input As String) As String
If input.Substring(input.Length - 1, 1) = " " Then input = input.Substring(0, input.Length - 3)
input = input.Replace("−", "-").Replace("x", "*").Replace("÷", "/").Replace(",", "")
Dim temp As Double = 0
Dim arr() As String = input.Split(" ")
If arr.Length > 1 Then
temp = New DataTable().Compute(If(arr(0).Contains("."), arr(0), arr(0) & ".0") & " " & arr(1) & " " &
If(arr(2).Contains("."), arr(2), arr(2) & ".0"), "")
If arr.Length > 3 Then
For i As Integer = 3 To arr.Length - 1 Step 2
temp = New DataTable().Compute(temp & " " & arr(i) & " " &
If(arr(i + 1).Contains("."), arr(i + 1), arr(i + 1) & ".0"), "")
Next
End If
Return temp
End If
Return input
End Function
Runtime is treating your expression 999999999 * 999999999 as a multiplication of two integer values, and trying to return it as an object which is the return type of Compute API. The output of multiplication of those numbers is resulting in a very large value which is crossing the maximum value which can be stored in a variable of int (System.Int32) data type.
It results in arithmetic overflow exception. To give a hint to the runtime so that it considers the expression as a multiplication of two double numbers please use following code:
dim str as string = "999999999.0 * 999999999.0"