SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Classes
Exercise:
Exercises
Question:11 | ISBN:9780136091813 | Edition: 2

Question

Add the following constructor to your Line class:
public Line(int x1, int y1, int x2, int y2)
Constructs a new Line that contains the given two Points.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

//package classes;

public class Line {
    
    Point point1;
    Point point2;
    
   // initialize the line class with the constructor
    public Line(Point Point1, Point point2) {
        this.point1 = Point1;
        this.point2 = point2;
    }
    
   // initialize the line class by passing the points
    public Line(int x1,int y1,int x2,int y2) {
        
        this.point1 = new Point(x1,y1);
        this.point2 = new Point(x2,y2);
    }
    
     public Point getPoint1() {
            return point1;
        }
        
        public Point getPoint2() {
            return point2;
        }
    
    // override the tostring to print the points
    public String toString() {
        return "[" +point1.toString()+", " +point2.toString()+"]";
    }
     
    //this method return the slope of two points
    public double getSlope() {
        if(point1.getX() == point2.getX())
            throw new IllegalArgumentException();
            
        double slope = (double) (point2.getY() - point1.getY()) / (point2.getX() - point1.getX());
        return slope;
    }


    public static void main(String[] args) {
        
        Line line = new Line(3,2,9,8);
        
        System.out.println("the string representation of the line is :"+line);
        System.out.println("slope of the line is: " +line.getSlope());
        
    }

}
Output:

the string representation of the line is :[(3,2), (9,8)]
slope of the line is: 1.0

 

0 0

Discussions

Post the discussion to improve the above solution.