Java Reference
In-Depth Information
final NumberBinding x3y1 = Bindings.multiply(x3, y1);
final NumberBinding x1y3 = Bindings.multiply(x1, y3);
final NumberBinding x2y1 = Bindings.multiply(x2, y1);
final NumberBinding x3y2 = Bindings.multiply(x3, y2);
final NumberBinding sum1 = Bindings.add(x1y2, x2y3);
final NumberBinding sum2 = Bindings.add(sum1, x3y1);
final NumberBinding sum3 = Bindings.add(sum2, x3y1);
final NumberBinding diff1 = Bindings.subtract(sum3, x1y3);
final NumberBinding diff2 = Bindings.subtract(diff1, x2y1);
final NumberBinding determinant = Bindings.subtract(diff2, x3y2);
final NumberBinding area = Bindings.divide(determinant, 2.0D);
x1.set(0); y1.set(0);
x2.set(6); y2.set(0);
x3.set(4); y3.set(3);
printResult(x1, y1, x2, y2, x3, y3, area);
x1.set(1); y1.set(0);
x2.set(2); y2.set(2);
x3.set(0); y3.set(1);
printResult(x1, y1, x2, y2, x3, y3, area);
}
private static void printResult(IntegerProperty x1, IntegerProperty y1,
IntegerProperty x2, IntegerProperty y2,
IntegerProperty x3, IntegerProperty y3,
NumberBinding area) {
System.out.println("For A(" +
x1.get() + "," + y1.get() + "), B(" +
x2.get() + "," + y2.get() + "), C(" +
x3.get() + "," + y3.get() + "), the area of triangle ABC is " + area.getValue());
}
}
We used
IntegerProperty
to represent the coordinates. The building up of the
NumberBinding area
uses all four
arithmetic factory methods of
Bindings
. Because we started with
IntegerProperty
objects, even though the return
type from the arithmetic factory methods of
Bindings
are
NumberBinding
, the actual object that is returned, up to
determinant
, are
IntegerBinding
objects. We used
2.0D
rather than a mere
2
in the
divide()
call to force the division
to be done as a
double
division, not as
int
division. All the properties and bindings that we build up form a tree
structure with
area
as the root, the intermediate bindings as internal nodes, and the properties
x1
,
y1
,
x2
,
y2
,
x3
,
y3
as leaves. This tree is similar to the parse tree we will get if we parse the mathematical expression for the area formula
using grammar for the regular arithmetic expressions.
When we run the program in Listing 4-5, the following output is printed to the console:
For A(0,0), B(6,0), C(4,3), the area of triangle ABC is 9.0
For A(1,0), B(2,2), C(0,1), the area of triangle ABC is 1.5
Search WWH ::
Custom Search