Java Reference
In-Depth Information
6. Add the following method to the TimeSpan class:
public void subtract(TimeSpan span)
Subtracts the given amount of time from this time span.
7. Add the following method to the TimeSpan class:
public void scale(int factor)
Scales this time span by the given factor. For example, 1 hour and 45 minutes scaled by 2 equals 3 hours and 30
minutes.
8. Add the following method to the Stock class:
public void clear()
Resets this Stock 's number of shares purchased and total cost to 0 .
9. Write a class called Line that represents a line segment between two Point s. Your Line objects should have the
following methods:
public Line(Point p1, Point p2)
Constructs a new Line that contains the given two Point s.
public Point getP1()
Returns this Line 's first endpoint.
public Point getP2()
Returns this Line 's second endpoint.
public String toString()
Returns a String representation of this Line , such as "[(22, 3), (4, 7)]" .
10. Add the following method to your Line class:
public double getSlope()
Returns the slope of this Line . The slope of a line between points ( x 1 , y 1 ) and ( x 2 , y 2 ) is equal to ( y 2 - y 1 ) / ( x 2 - x 1 ).
If x 2 equals x 1 the denominator is zero and the slope is undefined, so you may throw an exception in this case.
11. 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 Point s.
12. Add the following method to your Line class:
public boolean isCollinear(Point p)
Returns true if the given Point is collinear with the Point s of this Line —that is, if, when this Line is stretched
infinitely, it would eventually hit the given Point . Point s are collinear if a straight line can be drawn that connects
them. Two basic examples are three points that have the same x - or y -coordinate. The more general case can be
determined by calculating the slope of the line between each pair of points and checking whether this slope is the
same for all pairs of points. Use the formula ( y 2 - y 1 ) / ( x 2 - x 1 ) to determine the slope between two points ( x 1 , y 1 )
and ( x 2 , y 2 ). (Note that this formula fails for points with identical x -coordinates, so this will have to be a special case
in your code.) Since Java's double type is imprecise, round all slope values to a reasonable accuracy such as four
digits past the decimal point before you compare them.
Search WWH ::




Custom Search