Java

OOP GUIDE / WORK

 

POINT CLASS 2

 

 

TASK – PART 1 – CONSIDER THE FOLLOWING POINT CLASS

 

No work

 

 

TASK – PART 2 – TESTING THE POINT CLASS

 

Here is my Tester class:

 

public class PointTester

{

     public static void main(String[] args)

     {

           Point p1 = new Point(4,6);

           Point p2 = new Point(7,3);

          

           double d1 = p1.distanceFrom(p2.x, p2.y);

           System.out.println(d1);

 

           double d2 = p2.distanceFrom(p1.x, p1.y);

           System.out.println(d2);

     }

}

 

 

Note: Both d1 and d2 get the value 4.24.

 

TASK – PART 3 – ADDING A NEW METHOD

 

Here is my method:

 

 

     public double distanceFrom(Point q)

     {

           double dx = q.x - this.x;

           double dy = q.y - this.y;

           return Math.sqrt(dx * dx + dy * dy); 

     }

 

 

Note: A shorter solution would have been to simply call the other distanceFrom method.

 

TASK – PART 4 – MORE TESTING

 

Here is the code I added to the tester class to test the new method:

 

 

           double d3 = p1.distanceFrom(p2);

           System.out.println(d1);

 

           double d4 = p2.distanceFrom(p1);

           System.out.println(d2);

 

 

 

TASK – PART 5 – PROCESSING A POINT ARRAY

 

Here is the code I added to the PointTester class:

 

 

public class PointTester

{

     public static void main(String[] args)

     {

           Point[] polygon = new Point[9];

           polygon[0] = new Point(0, 0);

           polygon[1] = new Point(3, 2);

           polygon[2] = new Point(4, 1);

           polygon[3] = new Point(3, 5);

           polygon[4] = new Point(6, 3);

           polygon[5] = new Point(5, 8);

           polygon[6] = new Point(3, 9);

           polygon[7] = new Point(2, 6);

           polygon[8] = new Point(1, 2);

          

          //Add your code here.

           double totalDistance = polygon[0].distanceFrom(polygon[8]);

           for (int i=0; i<polygon.length-1; i++)

           {

                totalDistance += polygon[i].distanceFrom(polygon[i+1]);

           }

           System.out.println("Perimeter: " + totalDistance);     }

}

 

 

Note: Perimeter is 29.6.