【解決方法】これを解決するにはどうすればよいですか:「インデックスが配列の範囲外でした。」


‘インデックスが配列の範囲外だった。’

私が試したこと:

Private Sub TextBox11_MouseHover(sender As Object, e As EventArgs) Handles TextBox11.MouseHover

        Dim inputNumber As Integer
        inputNumber = Val(TextBox11.Text)
        Dim years As Integer
        years = inputNumber \ 365

        Dim remainingDays As Integer
        remainingDays = inputNumber Mod 365

        Dim months As Integer
        months = remainingDays \ 30

        Dim days As Integer
        days = remainingDays Mod 30

        'تحديد عدد الأيام في الشهور المختلفة
        Dim daysInMonth(11) As Integer
        daysInMonth(0) = 31
        daysInMonth(1) = 28
        daysInMonth(2) = 31
        daysInMonth(3) = 30
        daysInMonth(4) = 31
        daysInMonth(5) = 30
        daysInMonth(6) = 31
        daysInMonth(7) = 31
        daysInMonth(8) = 30
        daysInMonth(9) = 31
        daysInMonth(10) = 30
        daysInMonth(11) = 31

        If months >= 2 Then
            daysInMonth(1) = 29
        End If

        
        While days >= daysInMonth(months - 1) '--problem here---('Index was outside the bounds of the array.') 
            days -= daysInMonth(months - 1)
            months += 1
            If months = 13 Then
                years += 1
                months = 1
            End If

        End While
  Label29.Text = years & " years, " & months & " months, " & days & " days"

End Sub

解決策 1

1年は何ヶ月ありますか? :笑う:
あなたのコードを見てください:

VB
Dim daysInMonth(11) As Integer
daysInMonth(0) = 31
daysInMonth(1) = 28
daysInMonth(2) = 31
daysInMonth(3) = 30
daysInMonth(4) = 31
daysInMonth(5) = 30
daysInMonth(6) = 31
daysInMonth(7) = 31
daysInMonth(8) = 30
daysInMonth(9) = 31
daysInMonth(10) = 30
daysInMonth(11) = 31

11 個の整数を保持する配列を宣言してから、0 から 11 までのインデックスを埋めようとします。これには、整数用に 12 個の「スロット」が必要です。
11 を 12 に変更すると、エラーはなくなります。

VB
Dim daysInMonth(12) As Integer
daysInMonth(0) = 31
daysInMonth(1) = 28
daysInMonth(2) = 31
daysInMonth(3) = 30
daysInMonth(4) = 31
daysInMonth(5) = 30
daysInMonth(6) = 31
daysInMonth(7) = 31
daysInMonth(8) = 30
daysInMonth(9) = 31
daysInMonth(10) = 30
daysInMonth(11) = 31

しかし、とにかく「マジックナンバー」を使うのは悪い考えです…

解決策 2

引用:
VB.NET
While days >= daysInMonth(months - 1) '--problem here

コードをデバッグする必要がありますが、エラーの位置から、 months 変数は最初に 0.

簡単なチェックでは、 (365×N)+0(365×N)+29 で終わります months = 0.

注意: 開始日を指定せずに、日数を日、月、および年に変換することはできません。 たとえば、1 月 1 日から 30 日は 30 日ですが、2 月 1 日から 30 日は 1 か月になり、年によって 1 日または 2 日になります。

コメント

タイトルとURLをコピーしました