封装点Point类和线段Line类。点有x,y属性,线段有起点和终点。主程序中创建2个点,用这两个点创建一条线段,输出线段的长度。要求:类封装完整,结果输出正确。
Line线段类
package zy;
class Line{//线段类
private Point p1,p2;//两个点类
public Line(Point p1,Point p2){//构造方法,传入两个Point类,保存到当前的Line类属性中
this.p1 = p1;
this.p2 = p2;
}
public double getLength(){//计算直线中两点的长度
return p1.distance(p2);//通过调用Point类的distance方法,返回p1点和p2点两者的长度
}
public String ToString(){
return "起点" + p1 + " 终点" + p2 ;
}
public Point getP1() {
return p1;
}
public void setP1(Point p1) {
this.p1 = p1;
}
public Point getP2() {
return p2;
}
public void setP2(Point p2) {
this.p2 = p2;
}
}
Point点类
package zy;
public class Point {
private int x, y;// x,y为点的坐标
//求两点之间的距离
public double distance(Point p1) {
return Math.sqrt((p1.x -this.x)*(p1.x -this.x)+(p1.y-this.y)*(p1.y-this.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;
}
public Point() {
super();
x = y =0;
}
public String toString() {
return "(" + x + "," + y + ")";
}
}
主程序
package zy;
import java.util.Random;
public class Main{
public static void main(String[] args) {
Random r = new Random();//生成随机数
//点1
Point p1 = new Point(r.nextInt(100),r.nextInt(100));
//点2
Point p2 = new Point(r.nextInt(100),r.nextInt(100));
Line line = new Line(p1,p2);
System.out.println(line.ToString());//调用Line类型的方法输出点的数据
System.out.printf("此线段的长度为:%.1f\n",line.getLength());//输出该线段中两顶点的距离,保留一位小数
}
}