为什么我的阵列超出范围?

时间:2014-10-05 03:41:06

标签: vb.net

Option Strict On
Option Explicit On
Module Module1
 Sub Main()
    Dim HowMany As Integer
    Dim nameArray(HowMany) As String
    Dim HourlyWageArray(HowMany) As Double
    Dim HoursWorkedArray(HowMany) As Integer
    Dim GrossPayArray(HowMany) As Double
    Dim x As Integer = 0

    Console.WriteLine("How many employees?")
    HowMany = CInt(Console.ReadLine())

    Do While x < HowMany
        Console.WriteLine("Employee name: ")
        nameArray(x) = CStr(Console.ReadLine())
        Console.WriteLine("Hourly rate: ")
        HourlyWageArray(x) = CDbl(Console.ReadLine())
        Console.WriteLine("Hours worked: ")
        HoursWorkedArray(x) = CInt(Console.ReadLine())
        If HoursWorkedArray(x) <= 40 Then
            GrossPayArray(x) = HourlyWageArray(x) * HoursWorkedArray(x)
        ElseIf HoursWorkedArray(x) > 40 Then
            GrossPayArray(x) = ((HoursWorkedArray(x) - 40) * (HourlyWageArray(x) * 1.5)) + (40 * HourlyWageArray(x))
        End If
        x = x + 1
    Loop
    Console.WriteLine("{0,12:c} {1,12} {2,12:c} {3,12:c}", nameArray, HourlyWageArray, HoursWorkedArray, GrossPayArray)


    Console.ReadLine()

End Sub

End Module

在第17行,nameArray(x)= CStr(Console.ReadLine()),我收到错误&#34;未处理的类型&#39; System.IndexOutOfRangeException&#39;发生&#34;

无论我为HowMany输入什么值,尝试输入第二个员工姓名时都会发生此错误。

1 个答案:

答案 0 :(得分:2)

在声明数组后,您正在定义HowMany。 nameArray在第三行定义,当HowMany可能为0时,nameArray将为零条目。在定义nameArray之前,您应该从控制台阅读HowMany。