Hi, I have a problem with java. Please help me with this question. Using recursi
ID: 3685202 • Letter: H
Question
Hi, I have a problem with java. Please help me with this question.
Using recursion, write a program to compute the area of a polygon shown. You can use the vertices 1, 2, and 3 and cut off a triangle and use the fact that a triangle with points 1(x_1, y_1), 2(x_2, y_2), and 3(x_3, y_3) as corners, has an area of: area=(x_1y_2 + x_2y_3 + x_3y_1 - y_1x_2 - y_2x_3 - y_3x_1) Then move to vertices 1, 3, and 4 and do the area calculation. Continue with 1, 4, and 5 and then 1, 5, and 6 to do the same. You stop the recursion when you run out of triangles.Explanation / Answer
/**
* The java program PolygonArea that calls the method polygonarea that
* prints the area of polygon formed by x and y array values
* */
//PolygonArea.java
public class PolygonArea {
public static void main(String[] args) {
double[] x = {7.0, 15.0, 11.0, 4.0};
double[] y = {12.0, 9.0, 2.0, 9.0};
int i = 0;
double area = 0;
//print points of x and y arrays
System.out.println("Polygon points: ");
for (int index = 0; index < x.length; index++) {
System.out.println("("+x[index]+","+y[index]+")");
}
//calling polygonarea method
area = polygonarea(x, y, i, area);
System.out.println("Area of polygon :");
System.out.println(area);
}
/**The method polygonarea takes arrays of double types, x and y
* and returns the area of polygon */
public static double polygonarea (double[] x, double[] y, int i, double area){
if (i == x.length-2){
//return area value
return Math.abs(area) ;
} else{
//find area of triangles formed by the points
//add to area
area += (x[0]*y[i+1] + x[i+1]*y[i+2] +
x[i+2]*y[0] - y[0]*x[i+1] -
y[i+1]*x[i+2] - y[i+2]*x[0])/2;
//calling recursively
return polygonarea(x, y, i+1, area);
}
}
}
Sample output:
Polygon points:
(7.0,12.0)
(15.0,9.0)
(11.0,2.0)
(4.0,9.0)
Area of polygon :
55.0
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.