在给定代码中Point已实现完成,Line类是部分实现。
请在Line类中实现以下功能:
(1)完成参数列表为(Point point,double slope)的构造方法,这两参数表示直线上的一点和直线的斜率
(2)完成参数列表为(Point p1,Point p2)的构造方法,这两个参数表示直线上的两个点,斜率slope通过下列公式计算:slope=(p2.y2-p1.y1)/(p2.x2-p1.x1)
注意斜率是double类型。
(3)完成参数列表为(int a,int b)的构造方法,这两个参数表示直线上距x轴的截距为a和y轴的截距b,表示这条直线包含两个点(a,0)和(0,b)。斜率slope的计算公式和(2)相同。
(4)实现判断两条线是否平行的方法isParallel。(平行条件:斜率相等,两条线平行)
- Java code
public class Point { private int x; private int y; public Point(int x,int y){ this.x=x; this.y=y; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; }}
- Java code
public class Line { private Point point; private double slope; public boolean isParallel(Line line) { return false; } public Line(Point point,double slope){ this.point=point; this.slope=slope; } public Line(Point p1,Point p2){//从这里开始实现 }}
------解决方案--------------------
这个Line类的成员是你自己写的还是给定的?
------解决方案--------------------
- Java code
public class Line { private Point point; private double slope; public double getSlope() { return slope; } public void setSlope(double slope) { this.slope = slope; } public Line(Point point, double slope) { this.point = point; this.slope = slope; } public Line(Point p1, Point p2) { this.slope = (p2.getY() - p1.getY()) / (p2.getX() - p1.getX()); } public Line(int a, int b) { this.slope = -b / a; } public boolean isParallel(Line line) { return this.getSlope() == line.getSlope(); }}
------解决方案--------------------
- Java code
//楼主可以参考一下public class Line { private Point point; private double slope; public boolean isParallel(Line line) { if(this.slope==line.slope)return true; return false; } public Line(Point point,double slope){ this.point=point; this.slope=slope; } public Line(Point p1,Point p2){ this(p1,p2.getY()-p1.getY()/(p2.getX()-p1.getX()));//调用上面的构造器,求得斜率 } public Line(int a,int b){ this(new Point(a,0),new Point(0,b)); } public static void main(String []args){ Line l1=new Line(new Point(0,1),2); Line l2=new Line(new Point(2,3),3); System.out.print(l1.isParallel(l2)); }}
------解决方案--------------------
斜率好求,注意分母是0的情况即可。
------解决方案--------------------
------解决方案--------------------
代码就不写了,因为都是直线所以只需要分别算出两天线起点之间的距离和终点之间的距离(三角函数或勾股定理),如果两个结果先等就表示平行,