我有一个包含一堆代码的段类。我一直坚持使用两种方法,isParallel和缩短方法。这是我到目前为止的代码(我有一个与此类相关联的点类):
public class Segment {
//two Points that hold endpoints of the segment
private Point p1, p2;
//Default constructor that will set the endpoints to new
//Points with values (0,0) and (4,4)
public Segment(){
this(0, 0, 4, 4);
}
//Parameterized constructor that accepts (int x1, int y1, int x2, int y2)
//and creates and sets the endpoints
public Segment(int x1, int x2, int y1, int y2){
this.p1 = new Point(x1, y1);
this.p2 = new Point(x2, y2);
}
//Parameterized constructor that accepts (Point p1, Point p2) and sets both
//the endpoints to a deep copy of the Points that are passed in.
public Segment( Point p1, Point p2){
this.p1 = new Point(p1.getX(), p1.getY());
this.p2 = new Point(p2.getX(), p2.getY());
}
//Copy constructor that accepts a Segment and initializes the data (of the
//new Segment being created) to be the same as the Segment that was received.
public Segment(Segment other){
p1 = other.getP1();
p2 = other.getP2();
}
public Point getP1(){
return p1;
}
public Point getP2(){
return p2;
}
//The length method returns the length of the Segment.In fact, this method is same as distanceTo method
//So we can use distanceTo method which is already defined in Point class
public double length(){
return (p1.distanceTo(p2));
}
//The translate method returns nothing and should translate, or shift,
//itself (the Segment) by the distances passed in
public void translate(int xmove, int ymove) {
p1.translate(xmove,ymove);
p2.translate(xmove,ymove);
}
//The midpoint method calculates and returns the midpoint of the Segment as a new Point
public Point midpoint(){
return (p1.halfWayTo(p2));
}
//The slope method returns the slope of the Segment as a double.
public double slope(){
return (double)(p2.getY() - p1.getY()) / (p1.getX() - p2.getX());
}
/**
* The isParallel method returns true/false depending on whether the current Segment
* is parallel to the Segment received. Think about how you can tell if two segments
* are parallel. Note: Two overlapping segments ARE parallel.
*/
public boolean isParallel( Segment s1 ){
{
/**
* The shorten method changes its (the Segment's) endpoints so that they are both halfway
* to the midpoint. Example: The segment (0,0)---(12,16) has midpoint (6,8). After
* calling the shorten method, the segment should be (3,4)---(9,12). Each endpoint
* has moved in toward the midpoint (which stayed the same). So (3,4) is halfway between
* (0,0) and (6,8) and (9,12) is halfway between (12,16) and (6,8).
*/
public void shorten();

有人可以让我知道如何在我的代码中使用这两种方法。我非常感谢你的帮助。
谢谢!
答案 0 :(得分:0)
我实际上在完成同样的任务!对于isParallel
方法,您需要检查并查看当前Segment的斜率是否与收到的Segment的斜率相同。我还没有采用缩短方法,所以我无法帮助你。
另外,在我的课堂上(因为我做同样的任务),我们不能使用getX()
和getY()
方法,因为它们会破坏整个目的学习封装。我们需要实际要求Point类计算点的信息。例如,使用斜率方法而不是返回return (double)(p2.getY() - p1.getY()) / (p1.getX() - p2.getX());
,我在Point内部创建了一个方法来计算称为calcSlope
的两个点的斜率。并在细分中Slope
方法内调用该方法:return p1.calcSlope(p2);
。
希望这有帮助!