设计一个继承了抽象类GeometricObject 的新的Triangle类。绘制Triangle 类和GeometricObject 类的UML图并实现Triangle类。编写测试程序,提示用户输入三角形的三条边、颜色以及一个表明该三角形是否填充的布尔值。程序应该使用这些边来创建一个Triangle对象,并根据用户的输入来设置color和filled属性。程序应该显示面积、周长、颜色以及表明是否被填充的真或假的值,请给我一个正确的代码
时间: 2023-06-19 21:08:05 浏览: 145
以下是Triangle类和GeometricObject类的UML图以及Triangle类的实现代码:
```java
// GeometricObject.java
public abstract class GeometricObject {
private String color;
private boolean filled;
public GeometricObject(String color, boolean filled) {
this.color = color;
this.filled = filled;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public boolean isFilled() {
return filled;
}
public void setFilled(boolean filled) {
this.filled = filled;
}
public abstract double getArea();
public abstract double getPerimeter();
}
// Triangle.java
public class Triangle extends GeometricObject {
private double side1;
private double side2;
private double side3;
public Triangle(double side1, double side2, double side3, String color, boolean filled) {
super(color, filled);
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
public double getSide1() {
return side1;
}
public void setSide1(double side1) {
this.side1 = side1;
}
public double getSide2() {
return side2;
}
public void setSide2(double side2) {
this.side2 = side2;
}
public double getSide3() {
return side3;
}
public void setSide3(double side3) {
this.side3 = side3;
}
@Override
public double getArea() {
// 使用海伦公式计算面积
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
@Override
public double getPerimeter() {
return side1 + side2 + side3;
}
@Override
public String toString() {
return "Triangle: side1 = " + side1 + " side2 = " + side2 + " side3 = " + side3;
}
}
// TestTriangle.java
import java.util.Scanner;
public class TestTriangle {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the three sides of the triangle: ");
double side1 = input.nextDouble();
double side2 = input.nextDouble();
double side3 = input.nextDouble();
System.out.print("Enter the color of the triangle: ");
String color = input.next();
System.out.print("Is the triangle filled (true/false)? ");
boolean filled = input.nextBoolean();
Triangle triangle = new Triangle(side1, side2, side3, color, filled);
System.out.println("The area of the triangle is " + triangle.getArea());
System.out.println("The perimeter of the triangle is " + triangle.getPerimeter());
System.out.println("The color of the triangle is " + triangle.getColor());
System.out.println("The triangle is" + (triangle.isFilled() ? " " : " not ") + "filled");
}
}
```
这是一个运行示例:
```
Enter the three sides of the triangle: 3 4 5
Enter the color of the triangle: red
Is the triangle filled (true/false)? true
The area of the triangle is 6.0
The perimeter of the triangle is 12.0
The color of the triangle is red
The triangle is filled
```
阅读全文