2016-01-22 141 views
0

我正在編寫一個Ceasaer函數,它接收一個字符串並通過Ceasear密碼的變體運行它,並返回編碼的文本。出於某種原因,我在沒有指定邊界的數組上發生索引超出範圍錯誤。爲什麼我得到這個異常,我該如何解決它?爲什麼我得到一個索引超出範圍例外?

VB.NET代碼:

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 
+1

所有這些數組都已聲明但未實例化 - 它們沒有大小,沒有要存儲的元素/插槽。請參閱[在Visual Basic中的數組](https://msdn.microsoft.com/library/wak0wfyt(v = vs.110).aspx) – Plutonix

+3

'Dim Intets As Integer(str.length-1)'將實例化數組n個元素,其中n =字符串str的長度。您必須相應地採用其他陣列。 –

+0

@Alex B.非常感謝:)這確實是世界上最好的問答網站! –

回答

1

您必須指定數組邊界,然後才能存取權限的元素:

Dim ints As Integer(str.length-1) 

將實例與n個元素,其中n =字符串長度數組海峽。 (小心:VB.NET數組長度是從零開始的,所以具有1個元素的數組被實例化爲array(0))。您必須相應地採用其他數組。

相關問題