VB Calculate max jumps - vb.net

I am reading a .csv file in my FindMaxJumps method I am trying to make a loop to find the highest amount of jumps and set that to the highest max jumps. I have jumps set up as a String to read the csv file but thought I need to convert to a single or integer to make the comparison for all the users:
complete code:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
'Variables for each user
Dim entryID(11) As String
Dim location(11) As String
Dim forename(11) As String
Dim surname(11) As String
Dim jumps(11) As String
Dim bibValues(11) As String
Dim maxJumps As Single
Dim jumpsCounter As Single
Call LoadAthletes(entryID, location, forename, surname, jumps)
Call CreateBibValues(bibValues, forename, surname, location)
Call FindMaxJumps(jumpsCounter, maxJumps, forename, surname, jumps)
End Sub
'Get details from reading a file
Private Sub LoadAthletes(ByRef entryID As String(), ByRef location As String(), ByRef forname As String(), ByRef surname As String(), ByRef jumps As String())
Dim filename As String
filename = "C:\Users\rk\source\repos\Scottish Jumping Jax\athletes.csv"
FileOpen(1, filename, OpenMode.Input)
For counter = 1 To 11
Input(1, entryID(counter))
Input(1, location(counter))
Input(1, forname(counter))
Input(1, surname(counter))
Input(1, jumps(counter))
Next
FileClose(1)
End Sub
Private Sub CreateBibValues(ByVal bibValues As String(), ByVal forename As String(), ByVal surname As String(), ByVal location As String())
Dim locationAscii(11) As Integer
Dim firstCharacter(11) As String
For counter = 1 To 11
firstCharacter(counter) = location(counter).Substring(0, 1)
locationAscii(counter) = Asc(location(counter))
bibValues(counter) = firstCharacter(counter) & surname(counter) & locationAscii(counter)
Next
Dim savedFile As String
savedFile = ("C:\Users\rk\source\repos\Scottish Jumping Jax\bibValues.csv")
FileOpen(1, savedFile, OpenMode.Output)
For counter = 1 To 11
PrintLine(1, bibValues(counter))
Next
FileClose(1)
End Sub
Private Sub FindMaxJumps(ByVal jumpsCounter As Single, ByVal maxJumps As Single, ByVal forename As String(), ByVal surname As String(), ByVal jumps As String())
End Sub
End Class

the corrected code
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Variables for each user
Dim entryID(11) As String
Dim location(11) As String
Dim forename(11) As String
Dim surname(11) As String
Dim jumps(11) As Integer
Dim bibValues(11) As String
Dim maxJumps As Integer
'Define Calls and Functions
Call LoadAthletes(entryID, location, forename, surname, jumps)
Call CreateBibValues(bibValues, forename, surname, location)
Call FindMaxJumps(maxJumps, jumps)
Call DisplayMaxJumpers(maxJumps, forename, surname, jumps)
Call TallyAthletes()
End Sub
'Get details from reading a file
Private Sub LoadAthletes(ByRef entryID As String(), ByRef location As String(), ByRef forname As String(), ByRef surname As String(), ByRef jumps As Integer())
Dim filename As String
filename = "C:\Users\rk\source\repos\Scottish Jumping Jax\athletes.csv"
FileOpen(1, filename, OpenMode.Input)
For counter = 1 To 11
Input(1, entryID(counter))
Input(1, location(counter))
Input(1, forname(counter))
Input(1, surname(counter))
Input(1, jumps(counter))
Next
FileClose(1)
End Sub
'Creates the BibValues and saves it to disk
Private Sub CreateBibValues(ByVal bibValues As String(), ByVal forename As String(), ByVal surname As String(), ByVal location As String())
'local var to determine Ascii converstion and what character to convert
Dim locationAscii(11) As Integer
Dim firstCharacter(11) As String
'Loop to assign Bib Values
For counter = 1 To 11
firstCharacter(counter) = forename(counter).Substring(0, 1)
locationAscii(counter) = Asc(location(counter))
bibValues(counter) = firstCharacter(counter) & surname(counter) & locationAscii(counter)
Next
'Save bibValues.csv to disk
Dim savedFile As String
savedFile = ("C:\Users\rk\source\repos\Scottish Jumping Jax\bibValues.csv")
FileOpen(1, savedFile, OpenMode.Output)
For counter = 1 To 11
PrintLine(1, bibValues(counter))
Next
FileClose(1)
End Sub
'Function to find max jumps
Public Function FindMaxJumps(ByVal maxJumps As Integer, ByVal jumps As Integer())
maxJumps = jumps(1)
For counter = 2 To 11
If jumps(counter) > maxJumps Then
maxJumps = jumps(counter)
End If
Next
MsgBox(maxJumps)
Return maxJumps
End Function
'Determines if current number of jumps equals max jumps and displays forename and surname
Private Sub DisplayMaxJumpers(ByVal maxJumps As Integer, ByVal forename As String(), ByVal surname As String(), ByVal jumps As Integer())
End Sub
' Displays how many finalists by location
Private Sub TallyAthletes()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Close()
End Sub
End Class

Related

Visual Basic school project

Visual Basic is not my primary language and I am trying to help my son with a school project and failing miserably. The program is suppose to read a file, create an ID and save it to disk. Everything works fine except for the last 2 procedures, determine the minimum swim time, (It does that) but I am trying to assign the firstName of the user to the fastestSwimmer and in the last procedure display the winner and min time.
the file it is reading is just a text file with formatted as FirstName,Surname,Age and Gender.
My fastest Swimmer is always passing a null reference to the method. Any help would be greatly appreciated.
this is the whole program:
Public Class Form1
Private Sub StartBtn_Click(sender As Object, e As EventArgs) Handles StartBtn.Click
Dim firstName(5) As String
Dim surname(5) As String
Dim age(5) As String
Dim gender(5) As String
Dim swimID(5) As String
Dim time(5) As Single
Dim fastestSwimmer As String
Dim minTime As Single
'Call Procedures
Call GetDetails(firstName, surname, age, gender)
Call CalcSwimID(swimID, firstName, surname, age, gender)
Call RaceTimes(time, firstName, surname)
Call CalcWinner(time, firstName, fastestSwimmer, minTime)
'Call WinnersCircle(fastestSwimmer, minTime)
End Sub
'Get details from reading a file
Private Shared Sub GetDetails(ByVal firstName As String(), ByVal surname As String(), ByVal age As String(), ByVal gender As String())
Dim filename As String
filename = "C:/Users/rk/source/repos/CleanFolder/SwimersChampionShip/details.txt"
FileOpen(1, filename, OpenMode.Input)
For counter = 1 To 5
Input(1, firstName(counter))
Input(1, surname(counter))
Input(1, age(counter))
Input(1, gender(counter))
Next
FileClose(1)
End Sub
'Create a Swimmers ID and save it back to disk
Private Shared Sub CalcSwimID(ByRef swimID As String(), ByRef firstName As String(), ByRef surname As String(), ByRef Age As String(), ByRef gender As String())
Dim genderAscii(5) As Integer
Dim firstCharacter(5) As String
For counter = 1 To 5
firstCharacter(counter) = firstName(counter).Substring(0, 1)
genderAscii(counter) = Asc(gender(counter))
swimID(counter) = genderAscii(counter) & "-" & firstCharacter(counter) & surname(counter) & "-" & Age(counter)
Next
Dim savedFile As String
savedFile = ("C:/Users/rk/source/repos/CleanFolder/SwimersChampionShip/competitorsID.txt")
FileOpen(1, savedFile, OpenMode.Output)
For counter = 1 To 5
PrintLine(1, swimID(counter))
Next
FileClose(1)
End Sub
' Gets the race times by input box
Private Shared Sub RaceTimes(ByRef time As Single(), ByRef firstName As String(), ByRef surname As String())
For counter = 1 To 5
time(counter) = InputBox(" Please enter the swim times for " & firstName(counter) & " " & surname(counter))
Next
'MsgBox(time)
End Sub
'This will calculate the winner
Private Sub CalcWinner(ByRef time As Single(), ByRef firstName As String(), ByVal fastestSwimmer As String, ByRef minTime As Single)
'MsgBox(time(1))
minTime = time(1) And fastestSwimmer = firstName(1)
For counter = 2 To 5
If time(counter) < minTime Then
minTime = time(counter) And fastestSwimmer = firstName(counter)
End If
Next
'MsgBox(minTime)
End Sub
' Displays winner of the race to the winners circle, Gold medal will be sent by mail!
Private Sub WinnersCircle(ByRef fastestSwimmer As String, ByRef minTime As Single)
ListBox1.Items.Add("Congradulations " & fastestSwimmer & " you are the winner your time was " & minTime & " seconds. A new world record!")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Close()
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
End Sub
End Class
In the CalcWinner method you use AND in the wrong way:
Private Sub CalcWinner(ByRef time As Single(), ByRef firstName As String(), ByVal
fastestSwimmer As String, ByRef minTime As Single)
'MsgBox(time(1))
minTime = time(1)
fastestSwimmer = firstName(1)
For counter = 2 To 5
If time(counter) < minTime Then
minTime = time(counter)
fastestSwimmer = firstName(counter)
End If
Next
'MsgBox(minTime)
End Sub
When you write
minTime = time(1) And fastestSwimmer = firstName(1)
VB will ADD the first time ( time(1)) and fastestSwimmer = firstName(1) which is 0 because fastestSwimmer is not equal to firstName(1) so that evaluates to 0

having no knowledge to do the project that displaying countries and cities in visual basic

Screenshot So at the moment I'm trying to create an application where there's a two listbox, one shows the countries, one shows the cities in those countries. Having clicked the city in the listbox, the richtextbox will display the information in a specific format, which is the same as screenshot I provide. Then, the picturebox will provide the picture of that cities. There're also two labels: population and rainfall, which shows the statistics of it, but I don't know how to trigger that when I click the city in the listbox. Also, I want to know how to make the text font bigger and smaller by a checkbox, of course BY CODE . I'm currently working on codes, but it seems that I'm going nowhere.
Public Class frmWorldCities
'---------------------------------------------------
'Description: Class-wide declarations
'
'Calls: fNumOfFiles
'---------------------------------------------------
Const cstrPath As String = "..\Data\gldfiles\"
Dim CIntNumofFiles As Integer = 78
Dim cstrFileNames(CIntNumofFiles - 1) As String
Dim cintFileLines(CIntNumofFiles - 1) As Integer
Dim cstrCityNames(CIntNumofFiles - 1) As String
Dim cstrFileCountryNames(CIntNumofFiles - 1) As String
Dim cstrPopulation(CIntNumofFiles - 1) As String
Dim cstrRainfall(CIntNumofFiles - 1) As String
Dim cstrInformation(CIntNumofFiles - 1) As String
Dim cstrPictureName(CIntNumofFiles - 1) As String
Private Sub frmWorldCities_Load(sender As Object, e As EventArgs) Handles Me.Load
'---------------------------------------------------------------------------
'Description: how the application should display while opening.
'---------------------------------------------------------------------------
Dim strTemp As String = ""
Dim intLines As Integer
Dim i As Integer
Dim j As Integer
FileOpen(1, cstrPath & "list.wcf", OpenMode.Input)
Input(1, strTemp)
intLines = CInt(strTemp)
For i = 0 To intLines - 2
Input(1, cstrFileNames(i))
lstCities.Items.Add(cstrFileNames(i))
Next i
FileClose(1)
For i = 0 To cstrFileNames.Length - 1
FileOpen(1, cstrPath & cstrFileNames(i), OpenMode.Input)
Input(1, strTemp)
cintFileLines(i) = CInt(strTemp)
cstrCityNames(i) = LineInput(1)
Input(1, strTemp)
Input(1, cstrFileCountryNames(i))
cstrPopulation(i) = LineInput(1)
Input(1, cstrRainfall(i))
Input(1, strTemp)
For j = 0 To cintFileLines(i) - 10
strTemp = LineInput(1)
cstrInformation(i) &= strTemp & Chr(13)
Next j
Input(1, strTemp)
Input(1, cstrPictureName(i))
FileClose(1)
Next i
End Sub
Private Sub lstCountries_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstCountries.SelectedIndexChanged
'------------------------------------
'Description: listing the cities.
'------------------------------------
Dim i As Integer
lstCities.Items.Clear()
For i = 0 To cstrCityNames.Length - 1
If lstCountries.SelectedItem.ToString = cstrFileCountryNames(i) Then
lstCities.Items.Add(cstrCityNames(i))
End If
Next i
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
' To close the application
Me.Close()
End Sub
Private Sub chkBold_CheckedChanged(sender As Object, e As EventArgs) Handles chkBold.CheckedChanged
' To make the information bold.
If chkBold.Checked = True Then
rtbInformation.Font = New Font(rtbInformation.Font, FontStyle.Bold)
Else
rtbInformation.Font = New Font(rtbInformation.Font, FontStyle.Regular)
End If
End Sub
Private Sub chkItalic_CheckedChanged(sender As Object, e As EventArgs) Handles chkItalic.CheckedChanged
If chkItalic.Checked = True Then
rtbInformation.Font = New Font(rtbInformation.Font, FontStyle.Italic)
Else
rtbInformation.Font = New Font(rtbInformation.Font, FontStyle.Regular)
End If
End Sub
Private Sub chkBiggerFont_CheckedChanged(sender As Object, e As EventArgs) Handles chkBiggerFont.CheckedChanged
If chkBiggerFont.Checked = True Then
rtbInformation.Font = New Font(rtbInformation.Font, FontStyle.Strikeout)
End If
End Sub
Private Sub chkSmallerFont_CheckedChanged(sender As Object, e As EventArgs) Handles chkSmallerFont.CheckedChanged
End Sub
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles picCities.Click
End Sub
End Class

Edit Button: Conversion from string "name" in the datagrid view

I'm trying to edit a selected row from my Datagridview. When I try to change something in the textboxes, I get an error message for the first name and last name textboxes, stating: "Conversion from string "name" to type integer is not valid. If anyone could help me figure out what I'm doing wrong it would be greatly appreciated.
Dim dbo As New OwnersDataContext
Dim theowner As New Owners
Dim index As Integer
Private Sub DGV1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DGV1.CellContentClick
index = e.RowIndex
Dim selectedRow As DataGridViewRow
selectedRow = DGV1.Rows(index)
txtid.Text = selectedRow.Cells(0).Value.ToString
txtfname.Text = selectedRow.Cells(1).Value.ToString
txtlname.Text = selectedRow.Cells(2).Value.ToString
txtaddress.Text = selectedRow.Cells(3).Value.ToString
txtcity.Text = selectedRow.Cells(4).Value.ToString
cbostates.SelectedItem = selectedRow.Cells(5).Value.ToString
txtzipcode.Text = selectedRow.Cells(6).Value.ToString
End Sub
Private Sub btnEdit_Click(sender As Object, e As EventArgs) Handles btnEdit.Click
If DGV1.SelectedRows.Count < 0 Then
MessageBox.Show("Select owner")
Else
**If theowner.Update(txtid.Text, txtfname.Text, txtlname.Text, txtaddress.Text, txtcity.Text, CStr(cbostates.SelectedItem), txtzipcode.Text) = 0** Then
MessageBox.Show("New Owner could not be saved to database. Please check input.")
Else
Me.Close()
'refill the tbl with the updated
Dim q = From o In dbo.Owners
Select o.Owner_ID, o.Owner_FirstName, o.Owner_LastName, o.Address, o.City, o.State, o.ZipCode
DGV1.DataSource = q
End If
End If
End Sub
Added the update method from my class
Public Function Update(ByVal pOwnerID As Integer, ByVal pfname As String,
ByVal plname As String, ByVal pAddress As String, ByVal pCity As String, ByVal pState As String, ByVal pZipCode As Integer) As Integer
Return mytableadapter.Update(pfname, plname, pAddress, pCity, pState, pZipCode, pOwnerID) > 0
End Function

How to pass all value of ListBox Control to a function?

I am writing a simple application to read the value a textbox and add to a listbox control . But i have to pass the listbox control to function . Any suggestion ?
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
test("E:\Satyajit.txt")
End Sub
Public Function test(ByVal filename As String)
Dim FILE_NAME As String = filename
Dim TextLine As String
Dim result As String = Path.GetFileName(FILE_NAME)
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
words = TextLine.Split(New Char() {","c})
ListBox1.Items.Add(words(3) & "," & words(4))
objItem = ListView1.Items.Add(words(3) & "," & words(4))
Loop
test1(ListBox1.Items)//pass the listbox value hare
End Function
Public Function test1(ByVal value As String)
Dim Fest As String = value
MsgBox(Fest)
End Function
You're passing the contents of a ListBox to a method that is just displaying them in a MsgBox(). There are two approaches you can do to accomplish what I think you're wanting.
You can pass ListBox.Items to the method and iterate through each item concatenating them into a single String or StringBuilder, then pass the String to the MsgBox(). This approach makes your method dependent on ListBoxItems.
You can iterate through ListBox.Items concatenating them into a single String or StringBuilder, then pass the String to your method. This makes your method a little more scalable.
I recommend approach #2, something like:
Dim MyListBox As New ListBox
MyListBox.Items.Add("Item1")
MyListBox.Items.Add("Item2")
MyListBox.Items.Add("Item3")
MyListBox.Items.Add("Item4")
MyListBox.Items.Add("Item5")
Dim sb As New StringBuilder
For Each Item In MyListBox.Items
sb.AppendLine(Item)
Next
Test1(sb.ToString())
The Test1 method would look like:
Public Sub Test1(ByVal value As String)
MsgBox(value)
End Sub
Results:
You could pass the whole control to the function:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim lstbox As New ListBox
lstbox.Items.Add("Hello")
lstbox.Items.Add("Second Item")
lstbox.Items.Add("Third Item")
MsgBox("The list contains: " & Length(lstbox) & " characters")
End Sub
Function Length(ByVal ctrl As ListBox) As Integer
Dim TotalNumberOfItems As Integer = 0
For Each item As String In ctrl.Items.ToString
TotalNumberOfItems += 1
Next
Return TotalNumberOfItems
End Function
or just its items
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim lstbox As New ListBox
lstbox.Items.Add("Hello")
lstbox.Items.Add("Second Item")
lstbox.Items.Add("Third Item")
MsgBox("The list contains: " & Length(lstbox.Items) & " characters")
End Sub
Function Length(ByVal col As ListBox.ObjectCollection) As Integer
Dim TotalNumberOfCharacters As Integer = 0
For Each item As String In col
TotalNumberOfCharacters += item.Length
Next
Return TotalNumberOfCharacters
End Function

Reading from and manipulating a .csv file

I have multiple .csv files for each month which go like:
01/04/2012,00:00,7.521527,80.90972,4.541667,5.774305,7,281.368
02/04/2012,00:00,8.809029,84.59028,6.451389,5.797918,7,274.0764
03/04/2012,00:00,4.882638,77.86806,1.152778,15.13611,33,127.6389
04/04/2012,00:00,5.600694,50.35417,-3.826389,15.27222,33,40.05556
The format is : Date in the form dd/mm/yy,Current time,Current temperature,Current humidity,Current dewpoint,Current wind speed,Current wind gust,Current wind bearing
The program needs to calculate the average for
temperature
humidity
wind speed
wind direction
and display them on a text box.
any ideas?
Here is what I have done so far...
Option Strict On
Option Explicit On
Imports System.IO
Imports System
Public Class Form1
Private Sub cmb1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmb1.SelectedIndexChanged
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnexit.Click
Me.Close()
End Sub
Private Sub btn1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btndata.Click
'This is for August
If cmb1.SelectedIndex = 1 Then
TextBox1.Clear()
Using reader As New StreamReader("c://temp/DailyAug12log.csv")
Dim line As String = reader.ReadLine()
Dim avgTemp As Integer
Dim fields() As String = line.Split(",".ToCharArray())
Dim fileDate = CDate(fields(0))
Dim fileTime = fields(1)
Dim fileTemp = fields(2)
Dim fileHum = fields(3)
Dim fileWindSpeed = fields(4)
Dim fileWindGust = fields(5)
Dim fileWindBearing = fields(6)
While line IsNot Nothing
counter = counter + 1
line = reader.ReadLine()
End While
avgTemp = CInt(fields(2))
avgTemp = CInt(CDbl(avgTemp / counter))
TextBox1.Text = TextBox1.Text & "Month = August" & vbCrLf & "Temperature Average: " & avgTemp & vbCrLf
End Using
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim files() As String
files = Directory.GetFiles("C:\Temp", "*.csv", SearchOption.AllDirectories)
For Each FileName As String In files
cmb1.Items.Add(FileName.Substring(FileName.LastIndexOf("\") + 1, FileName.Length - FileName.LastIndexOf("\") - 1))
Next
End Sub
End Class
Private Class Weather
Public SampleTimeStamp AS Date
Public Temperature AS Double
Public Humidity As Double
Public WindSpeed AS Double
Public WindBearing AS Double
End Class
Sub Main
Dim samples = ReadFile("c://temp/DailyAug12log.csv")
Dim avgTemperature = samples.Average(Function(s) s.Temperature)
...
End Sub
Private Function ReadFile(ByVal fileName as String) AS List(Of Weather)
Dim samples As New List(Of Weather)
Using tfp As new TextFieldParser(filename)
tfp.Delimiters = new String() { "," }
tfp.TextFieldType = FieldType.Delimited
While Not tfp.EndOfData
Dim fields = tfp.ReadFields()
Dim sample As New Weather()
sample.SampleTimeStamp = Date.ParseExact(fields(0) & fields(1), "dd\/MM\/yyyyHH\:mm", CultureInfo.InvariantCulture)
sample.Temperature = Double.Parse(fields(2), CultureInfo.InvariantCulture)
sample.Humidity = Double.Parse(fields(3), CultureInfo.InvariantCulture)
sample.WindSpeed = Double.Parse(fields(4), CultureInfo.InvariantCulture)
sample.WindBearing = Double.Parse(fields(5), CultureInfo.InvariantCulture)
samples.Add(sample)
End While
Return samples
End Using
End Function
I would not use a this aprroach - if the order of the columns changes, your program will show wrong results.
I would use a good csv reader like http://kbcsv.codeplex.com/ and read the Data to a datatable. then you can calculate your resulting columns quite easily and reliablly, because you can adress each column like MyDatatable.Cooumns["Headername"].