Courses‎ > ‎AP Computer Science‎ > ‎Konstantinovich‎ > ‎

2018-10-09

posted Oct 9, 2018, 6:03 AM by Konstantinovich Samuel   [ updated Oct 9, 2018, 6:04 PM ]
- Pass Up Homework while I pass out exams
- Go over Exams
- Discuss homework

Homework:
Write the Triangle/Point class
Repo: MKS21X-Triangle
Use my Point as a base if you need to. You need to have getX/Y, distance/distanceToand both constructors. 
You should add a toString method!

Triangle needs
2 constructors (3 points / 6 doubles)
3 accessors:
    double getPerimeter()
    Point getVertex(int index) : return a COPY of the specified Point (0,1, or 2)
    String toString : format "Triangle: A(23.0,4.0) B(-2.3,5.001) C(5.0,0.52)"
1 mutator
    void setVertex(int index, Point newP) - replace the specified Point (0,1, or 2) with the new Point

Write a separate driver to test. You may all collaborate on the driver for testing purposes using the google group.


Classwork:

//immutable point class:
public
class Point{ private double x,y; public Point(double X, double Y){ x=X; y=Y; }

  public Point(Point p){
    x= p.x;
    y= p.y;
  }

public double getX(){ return x; } public double getY(){ return y; } }

//driver class
public
class demo{

  /* more methods can go here*/
  public static void main(String[]args){
    Point P1 = new Point(1,1);
    Point P2 = new Point(2,2);
    //for the 3 distance functions below Determine: 
    //a)static/non-static
//b)what class the method is located in
//System.out.println( distance(P1,P2)); //static in the demo class
System.out.println( Point.distance(P1,P2)); //static in the Point class
System.out.println( P1.distanceTo(P2)); //non-static in the Point class.
    //It is IMPLIED strongly that this is non static because you need info from P1 to calculate the distance
    //You cannot tell by the calling style alone, this is why we prefer to use CLASS.Method() for static calls.
} }
 

---------INSIDE THE POINT CLASS CONSIDER THE FOLLOWING------------------

//constructor takes one value per instance variable
public Point(double nx, double ny){
  x = nx;
  y = ny;
}

//constructor takes an other point to copy
public Point(Point p){
  x = p.x
  y = p.y;
}

//method that returns a new copy of 'this'
public Point copy(){
    return new Point(x,y); //this.x and this.y
    //OR
    //return new Point(this);
}


----IN A MAIN:-----
//to make 3 points with the same values, but that are 
//different instances:
Point P1 = new Point(3.45,5.99);
Point P2 = P1.copy(); //using copy
Point P3 = new Point(P1);//using the constructor




Comments