Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Program is Visual Studio 2012. Here is an code for encrypting i\'m trying to use

ID: 3796405 • Letter: P

Question

Program is Visual Studio 2012. Here is an code for encrypting i'm trying to use but i'm having trouble with the "key(j) = KeyString.Substring(j, 1)". Keep getting an error code "Index and length must refer to a location within the string." How can i fix this.

Private Sub encrypt_Click(sender As Object, e As EventArgs) Handles encrypt.Click

Dim key(3) As Integer
Dim i, j, CharASCII, KeyDigit, ComboBox As Integer
Dim CurrentChar, KeyString As String

KeyString = ComboBox

For i = 0 To RichTextBox1.Text.Length - 1

CurrentChar = RichTextBox1.Text.Substring(i, 1)
If Asc(CurrentChar) = 13 Then
RichTextBox1.Text = RichTextBox1.Text + Chr(13)
ElseIf Asc(CurrentChar) = 10 Then
RichTextBox1.Text = RichTextBox1.Text + Chr(10)
Else
KeyDigit = i Mod 4
For j = 0 To 3
key(j) = KeyString.Substring(j, 1)
Next
CharASCII = Asc(CurrentChar) + key(KeyDigit)

If CharASCII > 126 Then
CharASCII = CharASCII - 95
End If

ListBox1.Text = ListBox1.Text + Chr(CharASCII)
End If
Next
End Sub

Explanation / Answer

Your Code:

Private Sub encrypt_Click(sender As Object, e As EventArgs) Handles encrypt.Click

Dim key(3) As Integer
Dim i, j, CharASCII, KeyDigit, ComboBox As Integer
Dim CurrentChar, KeyString As String

KeyString = ComboBox

For i = 0 To RichTextBox1.Text.Length - 1

CurrentChar = RichTextBox1.Text.Substring(i, 1)
If Asc(CurrentChar) = 13 Then
RichTextBox1.Text = RichTextBox1.Text + Chr(13)
ElseIf Asc(CurrentChar) = 10 Then
RichTextBox1.Text = RichTextBox1.Text + Chr(10)
Else
KeyDigit = i Mod 4
For j = 0 To 3
key(j) = KeyString.Substring(j, 1)
Next
CharASCII = Asc(CurrentChar) + key(KeyDigit)

If CharASCII > 126 Then
CharASCII = CharASCII - 95
End If

ListBox1.Text = ListBox1.Text + Chr(CharASCII)
End If
Next
End Sub

The problem:

You are getting that error because, you have defined key as key(3) and in the loop you are executing till 0-3 (means 0,1,2,3). You have defined key as an array of 3 variables but you are assigning values at the 4th location which doesn't exist. That's why you are seeing this error.

Define the key as key(4). Your code will work perfectly.