0

How to fix from this code?

Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
    Dim a As Double = 0
    Dim j As Integer = poly.n - 1
    Dim i As Integer

    For i = 0 To poly.n Step 1
        a = a +((poly.Elmt(j).x + poly.Elmt(i).x) * (poly.Elmt(j).y - poly.Elmt(i).y))
        j = i
    Next

    a = Math.Abs(a / 2)
    MessageBox.Show("Area of The Polygon: " & a & " ")
End Sub
eglease
  • 2,445
  • 11
  • 18
  • 28
  • Does this answer your question? [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) – Yong Shun Mar 27 '21 at 05:58
  • 1
    Off-by-one bug, use For i = 0 To poly.n-1. j = i doesn't look good either, maybe j = j-1 – Hans Passant Mar 27 '21 at 10:44

1 Answers1

0

Put -1 in for loop declaration after poly.n as Young Sun wrote.

    For i = 0 To poly.n -1 Step 1

And check always j is not smaller than 0.

    Dim j As Integer = poly.n - 1
    If j < 0 Then Exit Sub

or put your calculation in try catch

        Try
            a = a + ((poly.Elmt(j).x + poly.Elmt(i).x) * (poly.Elmt(j).y - poly.Elmt(i).y))
        Catch ex As Exception

        End Try
Zserigta
  • 52
  • 9