Null Spark
Null Spark

Reputation: 409

Why am I getting an Index Out Of Range Exception?

I am writing a Ceasaer Function that takes a string and runs it through a variant of the Ceasear cipher, and returns the encoded text. For some reason I am getting an Index Out Of Range error on an Array declared with no specific bounds. Why am I getting this exception, and how do I fix it?

VB.NET Code:

Public Shared Function Ceaser(ByVal str As String) As String
    Dim r As String = ""
    Dim ints() As Integer = {}
    Dim codeints As Integer() = {}
    Dim codedints As Integer() = {}
    Dim ciphertext As String = ""
    For i As Integer = 0 To str.Length - 1
        Dim currentch As Integer = Map(str(i))
        ints(i) = currentch 'Where exception is happening
    Next
    Dim primes As Integer() = PrimeNums(ints.Length)
    For i As Integer = 0 To primes.Length - 1
        codeints(i) = ints(i) + primes(i) - 3
    Next
    For i As Integer = 0 To codeints.Length - 1
        Dim currentnum As Integer = codeints(i) Mod 27
        codedints(i) = currentnum
    Next
    For i As Integer = 0 To codedints.Length - 1
        Dim letter As String = rMap(codeints(i))
        ciphertext += letter
    Next
    Return ciphertext
End Function

Upvotes: 0

Views: 82

Answers (1)

Alex B.
Alex B.

Reputation: 2167

You have to specify the array bounds before you can acces its elements:

Dim ints As Integer(str.length-1) 

will instantiate the array with n elements where n = length of string str.

(Take care: VB .NET array lengths are zero-based, so an array with 1 element is instantiated with array(0)).

You have to adopt the other arrays accordingly.

Upvotes: 1

Related Questions