都说两点确定一条直线,那么设计一个直线类Line,需要通过两个点Point对象来确定。Line类具体要求如下: 1)定义两个Point对象p1,p2; 2)写出有参构造方法,传递两个对象值给p1,p2 3)为p1,p2写出setters,和getters方法 4)为Line写出一个getLength方法求直线中两点的长度 5) 为LIne写一个ToString方法,方法如下所示: public String toString() { return "Line [p1=" + p1 + ", p2=" + p2 + "]"; } 在Main类的main方法中,定义一个Line数组,数组长度通过键盘给出,然后通过键盘为每线段的两个Point对象的坐标赋值,并生成相应Line对象放入数组中,循环数组,输出每条直线的信息,以及两个点之间的距离。 Point 类如下所示: 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) { super(); 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; } @Override public String toString() { return "Point [x=" + x + ", y=" + y + "]"; } }
时间: 2023-06-14 21:05:25 浏览: 143
下面是Line类的代码实现:
```
public class Line {
private Point p1, p2;
public Line(Point p1, Point p2) {
super();
this.p1 = p1;
this.p2 = 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;
}
public double getLength() {
return p1.distance(p2);
}
@Override
public String toString() {
return "Line [p1=" + p1 + ", p2=" + p2 + "]";
}
}
```
在Main类的main方法中,实现对Line数组的输入和输出:
```
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入Line数组的长度:");
int n = scanner.nextInt();
Line[] lines = new Line[n];
for (int i = 0; i < n; i++) {
System.out.print("请输入第" + (i + 1) + "条直线的p1点的x坐标:");
int x1 = scanner.nextInt();
System.out.print("请输入第" + (i + 1) + "条直线的p1点的y坐标:");
int y1 = scanner.nextInt();
System.out.print("请输入第" + (i + 1) + "条直线的p2点的x坐标:");
int x2 = scanner.nextInt();
System.out.print("请输入第" + (i + 1) + "条直线的p2点的y坐标:");
int y2 = scanner.nextInt();
Point p1 = new Point(x1, y1);
Point p2 = new Point(x2, y2);
Line line = new Line(p1, p2);
lines[i] = line;
}
for (int i = 0; i < n; i++) {
System.out.println("第" + (i + 1) + "条直线是:" + lines[i].toString());
System.out.println("第" + (i + 1) + "条直线的长度是:" + lines[i].getLength());
}
}
```
阅读全文