By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,064 Members | 1,542 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,064 IT Pros & Developers. It's quick & easy.

Problem with Arrays

P: 6
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

Expand|Select|Wrap|Line Numbers
  1. Public Class Form1
  2.     Private Numbers(10) As Integer
  3.  
  4.     Private number As Integer
  5.     Private UpperBound As Integer
  6.  
  7.     Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
  8.         Dim sr As IO.StreamReader = IO.File.OpenText("Num.txt")
  9.  
  10.         For i As Integer = 0 To 20
  11.             number = CInt(sr.ReadLine)
  12.             Numbers(CInt(number)) += 1
  13.         Next
  14.         sr.Close()
  15.  
  16.         For i As Integer = 0 To 9
  17.             lstDisplay.Items.Add(Numbers(i))
  18.         Next
  19.  
  20.     End Sub
  21.  
May 5 '08 #1
Share this Question
Share on Google+
1 Reply


P: 20
Expand|Select|Wrap|Line Numbers
  1. Public Class Form1
  2.     Private Numbers(2,10) As Integer
  3.     Private number As Integer
  4.     Private UpperBound As Integer
  5.  
  6.     Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
  7.         Dim sr As IO.StreamReader = IO.File.OpenText("Num.txt")
  8.  
  9.         For i As Integer = 0 To 19     'before there were 21 loops for 20 lines?
  10.             number = CInt(sr.ReadLine)
  11.             If Numbers(0,CInt(number)) =0 then
  12.             Numbers(1,CInt(number))=i
  13.             End if
  14.             Numbers(0,CInt(number)) += 1
  15.         Next
  16.         sr.Close()
  17.  
  18.     End Sub
  19.  
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.
May 6 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.