Search code examples
arraylistvbscriptmscorlib

Does anyone know what "mscorlib: Index was out of range" means in my vbscript code?


Here is my code:

dim myArrayList

function addName

    Wscript.StdOut.WriteLine "What is your Quarterback's name?"
    n = Wscript.StdIn.ReadLine

    Wscript.StdOut.WriteLine "Attempts: "
    a = Wscript.StdIn.ReadLine

    Wscript.StdOut.WriteLine "Completions: "
    c = Wscript.StdIn.ReadLine

    Wscript.StdOut.WriteLine "Yards: "
    y = Wscript.StdIn.ReadLine

    Wscript.StdOut.WriteLine "Touchdowns: "
    t = Wscript.StdIn.ReadLine

    Wscript.StdOut.WriteLine "Interceptions: "
    i = Wscript.StdIn.ReadLine


Set myArrayList = CreateObject( "System.Collections.ArrayList" )
    myArrayList.Add n
    myArrayList.Add a
    myArrayList.Add c
    myArrayList.Add y 
    myArrayList.Add t
    myArrayList.Add i

end function 

addname()

function show
    for i = 1 to myArrayList.count
        Wscript.StdOut.WriteLine myArrayList(i)
    next
end function

show()

I receive an error that reads, "mscorlib: Index was out of range. Must be non-negative and must be less of the size of the collection. Parameter name: Index"

I don't know what the problem is Could anyone help me figure this out? Thanks.


Solution

  • The .NET System.Collections.ArrayList class uses 0-based indexes: The first element is at index 0, and the last element is at index Count - 1. The last iteration of your For loop causes the error because it attempts to access the element at index Count, which doesn't exist.

    Modify your For loop so that it counts from 0 to myArrayList.Count - 1 instead:

    For i = 0 To myArrayList.Count - 1
        WScript.StdOut.WriteLine myArrayList(i)
    Next