我有一个文本文件,我希望编写将数字放入数组的代码。
需要该程序从文本文件中读取每个成员的数据。然后,程序使用此数据查找并显示最大值。每个值大于最大值70%的成员的姓名都应写在一个空文本文件上,以便以后可以打印出该文件。
Nikolai,Bryant,145.6
Susan,Brown,34.2
Teressa,Jones,398.5
Martin,Daly,256.9
Ross,Durrant,409.0
Greg,Watson,99.2
Wendy,Russell,87.4
Pamela,Adkins,73.6
Ian,Hunter,385.7
James,Kerr,505.2
Lesley,Wallace,68.4
Kim,Pettigrew,256.4
Steven,Johnstone,23.4
Ali,Hussain,12.1
Hasan,Abbas,302.0
Jacek,Nowak,199.9
Mirka,Kowalski,176.8
Rudo,Hyper,120.2
Tisa,Sullivan,484.2
Albert,Nvodo,385.8
到目前为止,我所拥有的只是这个:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim FILE_NAME As String = "H:\S5\Computing\Programming\members.txt"
Dim objReader As New System.IO.StreamReader(FILE_NAME)
End Sub
End Class
答案 0 :(得分:0)
您将需要在代码文件的顶部添加Imports System.IO
。它有一个File
类,其中包含.ReadAllLines
方法。此方法将返回文本文件中所有行的数组。
'String.Split'将返回行中由逗号分隔(分隔)的字段的数组。 “,”后的小c告诉编译器这是Char
方法所期望的.Split
。
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim FILE_NAME As String = "H:\S5\Computing\Programming\members.txt"
Dim lines = File.ReadAllLines(FILE_NAME)
'Declare an array to hold your numbers VB arrays are declared arr(UBound)
'UBound is upper bound referring to highest index
'The highest index would be 1 less the lenght because indexes start at 0
Dim numbers(lines.Length - 1) As Single
Dim index As Integer 'Will be the index for the numbers array
'From the lines array we can loop through each line
For Each s As String In lines
Dim fields = s.Split(","c)
'Your fields array will have 3 elements, a first name at position (index) 0, last name at 1 and number at 2
'You only want the number - but it is not a number yet, it is still a string
'So we do a CSng to change it to a Single
numbers(index) = CSng(fields(2))
index += 1 'shortcut way to write index = index + 1
Next
For Each n As Single In numbers
Debug.Print(n.ToString)
Next
End Sub
@jmcilhinney在评论中建议的.TexFieldParser具有一些额外的功能,这些功能会派上用场,但这应该会让您入门。