我正在做一个VB.net凯撒密码

我正在做一个VB.net凯撒密码,vb.net,encryption,Vb.net,Encryption,你好 我很难完成这个作业:< 我正在做一个凯撒密码,用户将有一个txt文件 然后程序将找到文本文件并读取其中的内容 然后覆盖文本文件 到目前为止,我能做的代码,但我得到了一个 索引超出范围和nullreference异常 这是我的密码 Imports System.IO Public Class main_form Dim x, y, z, str_len As Integer 'where x is a counter for the array Dim loc, read

你好

我很难完成这个作业:< 我正在做一个凯撒密码,用户将有一个txt文件 然后程序将找到文本文件并读取其中的内容 然后覆盖文本文件

到目前为止,我能做的代码,但我得到了一个

索引超出范围和nullreference异常

这是我的密码

Imports System.IO


Public Class main_form
    Dim x, y, z, str_len As Integer 'where x is a counter for the array
    Dim loc, read(5), write(), str_1, str_2, aa As String

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

    End Sub

    Private Sub brw_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles brw_btn.Click
        TextBox1.Clear()
        OFD1.ShowDialog()
        TextBox1.Text = OFD1.FileName
        loc = OFD1.FileName
        read = File.ReadAllLines(OFD1.FileName)


    End Sub

    Private Sub enc_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles enc_btn.Click
        'Formula of Caesar's Cipher
        z = 1
        x = 0
        If read(x) <> "" Then

            While read(x) <> ""
                str_2 = ""
                str_1 = read(x)
                str_len = Len(str_1)
                MessageBox.Show(str_2)
                For i As Integer = 0 To str_len - 1
                    y = Asc(Mid(str_1, i + 1, i + 2))
                    y = y + Val(TextBox2.Text)
                    str_2 = str_2 + Chr(y)
                    MessageBox.Show(str_2)
                Next
                MessageBox.Show(str_2)
                write(x) = str_2
                File.AppendAllLines(OFD1.FileName, write(x))

                x += 1
            End While
        Else

        End If
    End Sub
End Class
谢谢

当然,您会得到超出范围的异常,因为:

While read(x) <> ""
    ...
    ...
    x += 1 'if x goes out of range the next loop in while will access read(x <-out of range) 
End While

Valter

这一异常发生在哪里?您是否已使用调试器完成此操作,以查看它试图访问的索引?当我删除这些行writex=str_2 File.AppendAllLinesOFD1.FileName、writex和hits时,会出现“索引超出范围”执行选项,在重写文本文件中的最后一行后,这些行位于:
While read(x) <> ""
    ...
    ...
    x += 1
    If x >= read.Length
        Exit While
    End If
End While
Dim write() as String
...
write(x) = str_2 '<-write is used un initialized, null reference exception
Private Sub enc_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles enc_btn.Click
    ReDim write(read.Length) '<---
    z = 1
    x = 0
    If read(x) <> "" Then
    ...
    ...