编写程序模拟用以表示直线的Line类,具体包含以下逻辑: ① 表示直线起点和终点的嵌套类Point,其包含描述横纵坐标的x、y字段。 ② 表示直线方向的嵌套枚举Direction,其包含描述若干方向的枚举常量。 在Line类中编写必要的代码,然后在测试类LineTest中构造几个Line对象并输出每个对象的有关信息。
时间: 2024-03-16 15:41:30 浏览: 16
Line类的实现如下:
```java
public class Line {
// 表示直线起点和终点的嵌套类Point
public static 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;
}
}
// 表示直线方向的嵌套枚举Direction
public enum Direction {
HORIZONTAL, VERTICAL
}
private Point startPoint;
private Point endPoint;
private Direction direction;
public Line(Point startPoint, Point endPoint) {
this.startPoint = startPoint;
this.endPoint = endPoint;
if (startPoint.getY() == endPoint.getY()) {
this.direction = Direction.HORIZONTAL;
} else if (startPoint.getX() == endPoint.getX()) {
this.direction = Direction.VERTICAL;
} else {
throw new IllegalArgumentException("Not a straight line");
}
}
public Point getStartPoint() {
return startPoint;
}
public void setStartPoint(Point startPoint) {
this.startPoint = startPoint;
}
public Point getEndPoint() {
return endPoint;
}
public void setEndPoint(Point endPoint) {
this.endPoint = endPoint;
}
public Direction getDirection() {
return direction;
}
public void setDirection(Direction direction) {
this.direction = direction;
}
@Override
public String toString() {
return "Line{" +
"startPoint=" + startPoint.getX() + "," + startPoint.getY() +
", endPoint=" + endPoint.getX() + "," + endPoint.getY() +
", direction=" + direction +
'}';
}
}
```
测试类LineTest的实现如下:
```java
public class LineTest {
public static void main(String[] args) {
Line.Point startPoint = new Line.Point(0, 0);
Line.Point endPoint = new Line.Point(5, 0);
Line line1 = new Line(startPoint, endPoint);
System.out.println(line1);
startPoint = new Line.Point(0, 0);
endPoint = new Line.Point(0, 5);
Line line2 = new Line(startPoint, endPoint);
System.out.println(line2);
startPoint = new Line.Point(0, 0);
endPoint = new Line.Point(5, 5);
try {
Line line3 = new Line(startPoint, endPoint);
} catch (IllegalArgumentException e) {
System.out.println("IllegalArgumentException: " + e.getMessage());
}
}
}
```
输出结果如下:
```
Line{startPoint=0,0, endPoint=5,0, direction=HORIZONTAL}
Line{startPoint=0,0, endPoint=0,5, direction=VERTICAL}
IllegalArgumentException: Not a straight line
```