Problem with Arrays

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • IanSD81
    New Member
    • Feb 2008
    • 6

    Problem with Arrays

    I am writing a program that takes a group of integers from a text file. There are 20 or them all between 0-9. I am trying to display the frequency of each digit in a list box. I thought I had the code correct but for some reason it’s off by one. Also I am drawing a blank when it comes to displaying the order of the numbers in the text file but only displaying each number once. My current code is listed down below. Any help would be awesome. Thanks

    Code:
    Public Class Form1
        Private Numbers(10) As Integer
    
        Private number As Integer
        Private UpperBound As Integer
    
        Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
            Dim sr As IO.StreamReader = IO.File.OpenText("Num.txt")
    
            For i As Integer = 0 To 20
                number = CInt(sr.ReadLine)
                Numbers(CInt(number)) += 1
            Next
            sr.Close()
    
            For i As Integer = 0 To 9
                lstDisplay.Items.Add(Numbers(i))
            Next
    
        End Sub
  • kuzen
    New Member
    • Dec 2006
    • 20

    #2
    Code:
    Public Class Form1
        Private Numbers(2,10) As Integer
        Private number As Integer
        Private UpperBound As Integer
    
        Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
            Dim sr As IO.StreamReader = IO.File.OpenText("Num.txt")
    
            For i As Integer = 0 To 19     'before there were 21 loops for 20 lines?
                number = CInt(sr.ReadLine)
                If Numbers(0,CInt(number)) =0 then
                Numbers(1,CInt(number))=i
                End if
                Numbers(0,CInt(number)) += 1
            Next
            sr.Close()
    
        End Sub
    I altered your code a bit...the second dimension I added to your array indicates the number of the line in your txt file at which some number starts appearing.
    Sorting the array out by this dimension you get the order of each number's appearance in the list. You will lose the numbers though since your numbers are apparently indices of Numbers() at the same time and sorting by the second dimension is about reindexing. You will probably need another dimension to keep the actual values independently.

    Comment

    Working...