【发布时间】:2015-05-15 03:43:44
【问题描述】:
我用 Java 编写了一些代码来计算多边形的面积。在我的代码中,我使用迭代“for”来获取 ArrayList 中 X 和 Y 坐标值的输入。我的代码计算运行成功,我确实得到了正确的输出。
我的问题是我想更改我的代码以使用递归,以便可以递归调用 computeArea(ArrayList c, int size),并且我不想在此方法中使用迭代“for”。
非常感谢那些能告诉我如何将此方法从迭代更改为递归的人。
谢谢。
下面是我的 Polygon.java 代码
import java.awt.geom.Point2D;
import java.util.ArrayList;
public class Polygon
{
private ArrayList<Point2D.Double> corners;
private double area;
private double adding;
private double minus;
private double exAdding;
private double exMinus;
public Polygon()
{
corners = new ArrayList<Point2D.Double>();
area = 0;
adding = 0;
minus = 0;
exAdding = 0;
exMinus = 0;
}
//add point to the array
public void add (Point2D.Double p)
{
corners.add(p);
}
//computes area of polygon
public double getArea()
{
return computeArea(corners, corners.size());
}
public double computeArea(ArrayList<Point2D.Double> c, int size)
{
if (size < 0)
{
return 0;
}
else
{
for (int i = 0; i < size-1; i++)
{
double xA = c.get(i).getX();
double yA = c.get(i).getY();
double xB = c.get(i+1).getX();
double yB = c.get(i+1).getY();
exAdding = c.get(size-1).getX()*c.get(size-size).getY();
adding = adding + xA*yB;
exMinus = c.get(size-1).getY()*c.get(size-size).getX();
minus = minus + yA*xB;
//System.out.println("test adding : " + adding);
}
//System.out.println("extra adding : " + exAdding);
area = Math.abs((adding+exAdding) - (minus+exMinus));
return area/2;
}
}
}
这是我的 PolygonTester.java 代码
import java.awt.geom.Point2D;
public class PolygonTester
{
public static void main (String[] args)
{
//create square
Polygon p = new Polygon();
p.add(new Point2D.Double(10, 20));
p.add(new Point2D.Double(20, 20));
p.add(new Point2D.Double(20, 10));
p.add(new Point2D.Double(10, 10));
System.out.println("Area : " + p.getArea());
System.out.println("Expected : 100");
//create square
Polygon p1 = new Polygon();
p1.add(new Point2D.Double(3, 4));
p1.add(new Point2D.Double(5, 11));
p1.add(new Point2D.Double(12, 8));
p1.add(new Point2D.Double(9, 5));
p1.add(new Point2D.Double(5, 6));
System.out.println("Area : " + p1.getArea());
System.out.println("Expected : 30");
//regular hexagon with radius 1
p = new Polygon();
for (int i = 0; i < 6; i++)
{
p.add(new Point2D.Double(Math.sin(i*Math.PI/3), Math.cos(i*Math.PI/3)));
}
System.out.println("Area : " + p.getArea());
System.out.println("Expected : " + 3*Math.sqrt(3)/2);
}
}
【问题讨论】:
-
你能不能写下,你为什么要使用递归?这段代码对我来说看起来不错,递归会给你的解决方案增加更多的复杂性,调用方法比简单的
for慢。老实说,我看不到如何在代码中包含递归的选项 - 它对于处理树等而不是普通数组很有用。 -
嗨一月,我想学习如何在我的代码中使用递归而不是迭代。因此,我可以思考和使用递归而不是仅迭代。
标签: java recursion arraylist polygon