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:10 | ISBN:9780136091813 | Edition: 2

Question

Add the following method to your Line class:
public double getSlope()
Returns the slope of this Line. The slope of a line between points (x1, y1) and (x2, y2) is equal to (y2 – y1) / (x2 – x1). If x2 equals x1 the denominator is zero and the slope is undefined, so you may throw an exception in this case.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

// package classes;

public class Line {
	
	Point point1;
	Point point2;
	
    // create constructor to initiate the line class
	public Line(Point Point1, Point point2) {
		this.point1 = Point1;
		this.point2 = point2;
	}
	
     // methods to get point1 and poit 2
	 public Point getPoint1() {
	        return point1;
	    }
	    
	    public Point getPoint2() {
	        return point2;
	    }
	
	public String toString() {
		return "[" +point1.toString()+", " +point2.toString()+"]";
	}
	
     // method to get  slope
	public double getSlope() {
        if(point1.getX() == point2.getX())
            throw new IllegalArgumentException();
            
        double slope = (double) (point2.getY() - point1.getY()) / (point2.getX() - point1.getX());
        return slope;
    }

    // driver method
	public static void main(String[] args) {
		
		Point point1 = new Point(3,6);
		Point point2 = new Point(7,8);
		
		Line line = new Line(point1,point2);
		
		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,6), (7,8)]
slope of the line is: 0.5

 

0 0

Discussions

Post the discussion to improve the above solution.