2015-05-28 2 views
0

Я пишу программу, которая должна искать определенный диапазон чисел в am Array. Число, которое мне нужно искать, на самом деле относится к тем классам, которые получил бы ученик, т.е. As, Bs, Cs, Ds, Es и Fs. Это мой код:Поиск конкретных чисел в массиве

Импорт System.IO Импорт System.Math

Открытый класс frmClassStatistics

'Arrays to hold the name and marks read from file 
Private strName() As String 
Private dblMark() As Integer 
Private intNumStudents As Integer = 0 
Private Average As Double 
Private StandardDeviation As Double 
Private arrHighestMark() As Double 

Private Sub frmClassStatistics_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 

    'Reads each student name and final mark from the mark file. It them separates each name from the mark 
    'and places the student names and the final mark into two, one-dimensional arrays. 
    'One array will be an array of string (for the names) and the other array will be an array of real numbers (for the marks). 

    Dim strFilename As String 
    Dim i As Integer 
    Dim intLastBlank As Integer 
    Dim strInput As String 
    Dim StudentMarks = "C:\StudentMarks.txt" 

    strFilename = "StudentMarks.txt" 

    If File.Exists(strFilename) Then 
     Dim srReader As New StreamReader(strFilename) 

     Try 

      i = 0 

      While Not srReader.EndOfStream 

       strInput = srReader.ReadLine() 

       'find location of TAB between the name and the mark. 
       intLastBlank = strInput.IndexOf(vbTab) 

       'take all characters before the TAB and place them into the name array 
       strName(i) = strInput.Substring(0, intLastBlank) 

       intNumStudents = intNumStudents + 1 

       'take all characters after the TAB, convert them into a real number and 
       'place them into the mark array 
       dblMark(i) = Double.Parse(strInput.Substring(intLastBlank + 1)) 

       i = i + 1 

      End While 

     Catch ex As Exception 
      MessageBox.Show("Problem reading data from the file") 
     End Try 

     srReader.Close() ' Close the file 

    End If 

End Sub 


Private Sub btnShowStatistics_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShowStatistics.Click 

    'Finds the dblMark array to find the class avarage, highest Mark and number of students above the class avarage 

    'I earased it for simplicity 

    Grades() 

End Sub 

Private Sub Grades() 

    Dim blnFound As Boolean = False 
    Dim intCount As Integer = 0 
    Dim intPosition As Integer 

"В тот момент, когда я запускаю программу, я получаю сообщение об ошибке говорит здесь, что нулевой Исключение ссылки не было обработано

Do While blnFound And intCount < dblMark.Length 
     If dblMark(intCount) >= 98 Then 
      blnFound = True 
      intPosition = intCount 
     End If 
     intCount += 1 
    Loop 
    'check to see if value found 
    If blnFound Then 
     txtAs.Text = intPosition 
    Else 
     txtAs.Text = 0 
    End If 

End Sub 

Я заполнил базу здесь, используя эту петлю? Есть ли более простой способ запрограммировать это?

+0

Если вы отлаживаете, вы должны заметить, что dblMark равно ничто. –

+0

Установить точку останова в приведенном выше коде и выполнить ее ... – Codexer

+0

Возможный дубликат [Что такое исключение NullReferenceException и как его исправить?] (Http://stackoverflow.com/questions/4660142/what-is-a -nullreferenceexception-и-как-делать-я-Fix-It) –

ответ

1

Прежде всего, вы никогда не изменяли размер dblMark(). Поэтому я удивлен, что вы не получаете ошибок в цикле, который загружает dblMark. Это заставляет меня думать, что ваш If FileExists() не нашел файл, и поэтому весь этот код пропускается.

Ошибка в конечном счете происходит потому, что ваша переменная dblMark равна nothing. Если вы присвоили ему значение или объявили его dblMark(0), ваша ошибка исчезнет, ​​но ваша программа, вероятно, не будет делать то, что вы хотите. Попробуйте использовать полный путь для strFilename (например, вы указали две строки выше: strFilename = "c:\studentmarks.txt)

Другие наблюдения: переменная dblMark() объявлена ​​как массив целых чисел, но вы анализируете как двойной (и название подразумевает двойное , вместо целого).