Skip to main content

Find the bug in the following code.

This code opens / creates / reads and writes / appends to text files as specified by the user. Assuming that the user has entered numeric, comma-separated data, the GetRange module calculates the range and the range coefficient (lookup Statistics - Measures of Dispersion Std XI). Somewhere in this last bit the program does a few mistakes.

Imports System.io
Public Class FileOps
    Public Response As Integer
    Private Sub ReadFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ReadFile.Click
        MyFileData.Clear()
        If CreateFile() > -1 Then MyFileData.Text = File.ReadAllText(MyFilePath.Text)
    End Sub

    Private Sub SaveToFile_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SaveToFile.Click
        If CreateFile() = -1 Then Exit Sub
        If File.ReadAllText(MyFilePath.Text).Length >= 0 Then
            Response = MsgBox("The file contains something already. Do you want to overwrite? (Clicking on 'No' will append to the file)", MsgBoxStyle.YesNoCancel)
            If Response = vbYes Then File.WriteAllText(MyFilePath.Text, MyFileData.Text)
            If Response = vbNo Then File.AppendAllText(MyFilePath.Text, vbCrLf & MyFileData.Text)
        End If
    End Sub
    Function CreateFile()
        CreateFile = -1
        If Not File.Exists(MyFilePath.Text) Then
            Response = MsgBox("File not found at the given path. Shall I create it?", MsgBoxStyle.YesNo)
            If Response = vbYes Then
                File.Create(MyFilePath.Text)
                CreateFile = 1
            Else
                Exit Function
            End If
        Else
            CreateFile = 0
        End If
    End Function

    Private Sub GetRange_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GetRange.Click
        Dim c As String, s As String, i As Integer, t As String, k As Integer, max As Single, min As Single, R As Single, RC As Single
        Dim N(100) As Single
        t = MyFileData.Text
        s = ""
        k = 0
        For i = 1 To t.Length
            If c <> "," And Mid(t, i, 2) <> vbCrLf Then
                s = s & c
            Else
                N(k) = CSng(s)
                s = ""
                k = k + 1
                If k = 100 Then
                    MsgBox("Array is full and there is still some data in the textbox / file. Truncating the data to get range")
                    Exit For
                End If
            End If
        Next
        max = N(0) : min = N(0)
        For i = 1 To N.GetUpperBound(0) - 1
            If N(i) > max Then max = N(i)
            If N(i) < min Then min = N(i)
        Next
        R = max - min
        RC = R / (max + min)
        MsgBox("The range of the data in the file is " & R & vbCrLf & "The Range coefficient is " & RC)
    End Sub
End Class

Comments