Quote:
Originally Posted by alex001
//Please skip down to the section where there is the line of code:
// points[i] = new Point(coords[i][0],coords[i][1]);
//and read the comments above it.
import Geometry.*; // Import the Point and Line classes
public class TryPackage {
public static void main(String[] args) {
double[][] coords = { {1.0, 0.0}, {6.0, 0.0}, {6.0, 10.0},
{10.0,10.0}, {10.0, -14.0}, {8.0, -14.0}};
// Create an array of points and fill it with Point objects
Point[] points = new Point[coords.length];
for(int i = 0; i < coords.length; ++i)
//The Line below I am having a hard time understanding. Why 0 and 1?
//What about the rest of the elements in the array? How are they accounted for?
points[i] = new Point(coords[i][0],coords[i][1]);
// Create an array of lines and fill it using Point pairs
Line[] lines = new Line[points.length - 1];
double totalLength = 0.0; // Store total line length here
for(int i = 0; i < points.length - 1; ++i) {
lines[i] = new Line(points[i], points[i+1]); // Create a Line
totalLength += lines[i].length(); // Add its length
System.out.println("Line "+(i+1)+' ' +lines[i] + " Length is " + lines[i].length());
}
// Output the total length
System.out.println("\nTotal line length = " + totalLength);
}
}
|
[code]
for(int i = 0; i < coords.length; ++i) {
points[i] = new Point(coords[i][0],coords[i][1]);
[code]
I can see where you're getting confused. Remember that coords is an array of pairs of co-ordinates. That is an array of arrays.
coords[0] is the pair {1.0, 0.0}, a 2 element array.
coords[0][0] is the double 1.0
coords[0][1] is the double 0.0
You could represent visually as a matrix like this
Code:
[0] [1]
[0] { 1.0, 0.0 }
[1] { 6.0, 0.0 }
[2] { 6.0, 10.0 }
[3] { 10.0, 10.0 }
...
Remember that the line you're getting confused about is /within/ a for loop.
When you see:
That means, on the first iteration of the loop, coords[0][0], which is the double 1.0. On the next iteration of the loop you'll be looking at coords[1][0] and coords[1][1].
Or visually
Code:
[0] [1]
i==[0] { 1.0, 0.0 }
i==[1] { 6.0, 0.0 }
i==[2] { 6.0, 10.0 }
i==[3] { 10.0, 10.0 }