我正在编写一个java项目,并由教师给我一个测试程序来测试我的代码。它们的接口有三个类。我的观点和我的水平段类通过了测试,但是我一直在斜率方法和构造函数的段类上得到错误!我已经做了一些修改来解决这些问题,但无法弄清楚我做错了什么。我发布了一个错误的屏幕截图。enter image description here
这是我的代码,当然是其中的一部分:
public class Segment implements SegmentInterface {
// two Points that hold endpoints of the segment
private Point p1;
private Point 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);
this.p1 = new Point(0, 0);
this.p2 = new Point(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 y1, int x2, int y2) {
//this.p1 = new Point(x1, y1);
//this.p2 = new Point(x2, y2);
if(x1 != x2 && y1 != y2){
this.p1 = new Point(x1, y1);
this.p2 = new Point(x2, y2);
}
else{
throw new IllegalArgumentException("undefined");
}
}
//A parameterized constructor that accepts (Point p1, Point p2) and sets both
//the endpoints to a deep copy of the Points that are passed in.
//Make sure to check to see if both Points are equal. This would be a
//theoretical "Segment" of length 0 which is not allowed, so throw a new
//IllegalArgumentException.
public Segment(Point p1, Point p2) {
if(p1 != p2){
this.p1 = new Point(p1.getX(), p1.getY());
this.p2 = new Point(p2.getX(), p2.getY());
}
else{
throw new IllegalArgumentException("Points cannot have same values!");
}
}
// 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) {
this(other.p1, other.p2);
//if(other.p1 == other.p2){
//throw new IllegalArgumentException("Undefine!");
//}
}
/*
* The slope method returns the slope of the Segment as a double. If the segment
* is vertical, the slope is undefined. In that case, Java will return
* Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY, depending on which way you
* subtract to calculate the slope. You can either check for division by zero or
* let Java do the calculation. However, your requirements are to ALWAYS return
* Double.POSITIVE_INFINITY if the slope is undefined.
*
* Also, strangely enough, Java may return 0 or -0 for a slope which is horizontal.
* Your requirements are to always return a slope of 0 for a horizontal line
* (don’t always just return the Java calculation).
*/
public double slope() {
if(p1.getY() == p2.getY()){
return 0;
}
else if(p1.getX() == p2.getX()){
double inf = Double.POSITIVE_INFINITY;
return inf;
}
else{
return ((double) (p2.getY() - p1.getY())
/ (p1.getX() - p2.getX()));
}
}
提前感谢您的帮助!!