(Triangle 类)设计一个继承了抽象类GeometricObject 的新的Triangle类。绘制Triangle 类和GeometricObject 类的UML图并实现Triangle类。编写测试程序,提示用户输入三角形的三条边、颜色以及一个表明该三角形是否填充的布尔值。程序应该使用这些边来创建一个Triangle对象,并根据用户的输入来设置color和filled属性。程序应该显示面积、周长、颜色以及表明是否被填充的真或假的值。
时间: 2023-06-19 07:08:38 浏览: 108
以下是Triangle类和GeometricObject类的UML图:
```
GeometricObject
-------------------------------
-color: String
-filled: boolean
-dateCreated: Date
-------------------------------
+GeometricObject()
+GeometricObject(color: String, filled: boolean)
+getColor(): String
+setColor(color: String): void
+isFilled(): boolean
+setFilled(filled: boolean): void
+getDateCreated(): Date
+toString(): String
+getArea(): double
+getPerimeter(): double
|
V
Triangle
-------------------------------
-side1: double
-side2: double
-side3: double
-------------------------------
+Triangle()
+Triangle(side1: double, side2: double, side3: double, color: String, filled: boolean)
+getSide1(): double
+setSide1(side1: double): void
+getSide2(): double
+setSide2(side2: double): void
+getSide3(): double
+setSide3(side3: double): void
+getArea(): double
+getPerimeter(): double
+toString(): String
```
以下是Triangle类的代码实现:
```java
import java.util.Date;
public class Triangle extends GeometricObject {
private double side1, side2, side3;
public Triangle() {
this(1.0, 1.0, 1.0, "white", false);
}
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;
}
public double getArea() {
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
public double getPerimeter() {
return side1 + side2 + side3;
}
public String toString() {
return "Triangle: side1 = " + side1 + " side2 = " + side2 + " side3 = " + side3;
}
}
```
以下是测试程序的代码实现:
```java
import java.util.Scanner;
public class TestTriangle {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter 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 or false)? ");
boolean filled = input.nextBoolean();
Triangle triangle = new Triangle(side1, side2, side3, color, filled);
System.out.println("Area: " + triangle.getArea());
System.out.println("Perimeter: " + triangle.getPerimeter());
System.out.println("Color: " + triangle.getColor());
System.out.println("Filled: " + triangle.isFilled());
}
}
```
阅读全文