Java Reference
In-Depth Information
// Output the total length
System.out.println("\nTotal line length = " + totalLength);
}
}
You should save this as TryPackage.java in the directory TryPackage . If the path to your
Geometry directory on a PC running Windows is C:\Packages\Geometry , you can compile this
with the command:
javac -classpath ".;C:\Packages" TryPackage.java
This assumes the current directory contains the TryPackage.java file. The -classpath option
specifies two paths separated by a semi-colon. The first path, specified by a period, is the current
directory. This is necessary to enable the TryPackage.java source file to be found. The second path
is C:\Packages , which is the directory containing our Geometry package. Without this the compiler
will not be able to find the classes in the Geometry package and the compilation will fail.
Once you have a successful compilation, you can execute the program with the command:
java -classpath ".;C:\Packages" TryPackage
When the program executes, you should see the following output:
Line 1 (1.0, 0.0):(6.0, 0.0) Length is 5.0
Line 2 (6.0, 0.0):(6.0, 10.0) Length is 10.0
Line 3 (6.0, 10.0):(10.0, 10.0) Length is 4.0
Line 4 (10.0, 10.0):(10.0, -14.0) Length is 24.0
Line 5 (10.0, -14.0):(8.0, -14.0) Length is 2.0
Total line length = 45.0
How It Works
This example is a handy review of how you can define arrays, and also shows that you can declare an
array of objects in the same way as you declare an array of one of the basic types. The dimensions of
the array of arrays, coords , are determined by the initial values that are specified between the braces.
The number of values within the outer braces determines the first dimension. Each of the elements in
the array is itself an array of length two, with each pair of element values being enclosed within their
own braces.
Since there are six sets of these, we have an array of six elements, each of which is itself an array of two
elements. Each of these elements correspond to the (x, y) coordinates of a point.
You can see from this that, if necessary, you can create an array of arrays with each row having a
different number of elements. The number of initializing values that appear, so they could all be
different in the most general case, determines the length of each row.
We declare an array of Point objects with the same length as the number of (x, y) pairs in the coords
array. This array is filled with Point objects in the for loop, which we created using the pairs of
coordinate values from the coords array.
Search WWH ::




Custom Search