Java Reference
In-Depth Information
You may know that there is a very simple formula to compute these numbers, but you
should pretend for now that you don't know about it. The ultimate purpose of this
section is not to compute triangle numbers, but to learn about the concept of recursion
in a simple situation.
Here is the the class that we will develop:
public class Triangle
{
public Triangle(int aWidth)
{
width = aWidth;
}
public int getArea()
{
È
}
private int width;
}
If the width of the triangle is 1, then the triangle consists of a single square, and its
area is 1. Let's take care of this case first.
588
589
public int getArea()
{
if (width == 1) return 1;
È
}
To deal with the general case, consider this picture.
[]
[] []
[] [] []
[] [] [] []
Suppose we knew the area of the smaller, colored triangle. Then we could easily
compute the area of the larger triangle as
smallerArea + width
How can we get the smaller area? Let's make a smaller triangle and ask it!
Triangle smallerTriangle = new Triangle(width - 1);
Search WWH ::




Custom Search