美好的一天,
我无法完成这项作业:< 我正在做一个caesar密码,用户将拥有一个txt文件 然后程序将找到文本文件并阅读其中的内容 然后覆盖文本文件
到目前为止,我能够完成代码,但我得到了索引超出范围和空引用异常
这是我的代码
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
谢谢!
答案 0 :(得分:0)
当然,您将超出范围异常,因为:
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
你必须插入
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
更改write() to write
或:
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
...
...
Valter