user10600191
user10600191

Reputation:

How to fix java.lang.IndexOutOfBoundsException error here?

What I'm trying to do is to create a polygon object, which consists of an ArrayList of Point2D objects and then find the perimeter of it.

Polygon Class

public void addPoint(Point2D.Double p) {
    point.add((Point2D.Double) p);
}

public double perimeter() {
    double perimeter = 0.0;

    for (int i = 0; i < point.size(); i++) {
        perimeter += point.get(i).distance(point.get(i + 1));
    }
    return perimeter;
}

Main Class

Polygon polygon1 = new Polygon();

Point2D.Double p1 = new Point2D.Double(10, 20);
Point2D.Double p2 = new Point2D.Double(20, 30);
Point2D.Double p3 = new Point2D.Double(10, 40);

polygon1.addPoint(p1);
polygon1.addPoint(p2);
polygon1.addPoint(p3);

System.out.println(polygon1.perimeter());

Upvotes: 1

Views: 99

Answers (2)

Dominik Wosiński
Dominik Wosiński

Reputation: 3874

You are getting the i + 1 object, which may not exist in the list when You are iterating. For example, if you have only one element in the list the for loop will start at the 0, so you will have something like this for i == 0 :

        perimeter += point.get(0).distance(point.get(0 + 1));

But You don't have the element with index 1 in the list so it will throw an exception.There are two ways of fixing this issue:

1) You can change the for loop to for (int i = 0; i < point.size()-1; i++). And then increase the perimeter for the last point manually after the for loop.

2) You can leave the loop as it is but simply add the condition:

if(i == point.size()-1`) {
        perimeter += point.get(i).distance(point.get(0));
}

Upvotes: 2

OneCricketeer
OneCricketeer

Reputation: 192023

point.get(i + 1) doesn't exist at the end of the loop

Use int i = 0; i < point.size() - 1

Upvotes: 2

Related Questions