用java1. 编程序,创建一个描述三角形的类Triangle,类中有三边长、面积、周长等成员变量,有带参数的构造方法,以及计算面积、计算周长和输出信息等成员方法,再创建描述圆形的类Circle,其中有半径、面积、周长等属性,有带参数的构造方法,以及计算面积、计算周长和输出信息等成员方法,在主类中测试三角形类和圆形类的使用(创建对象,计算面积、周长,输出信息)。
时间: 2023-06-12 08:06:45 浏览: 71
下面是Java代码实现:
```java
// Triangle类
public class Triangle {
private double side1;
private double side2;
private double side3;
private double area;
private double perimeter;
public Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
calculateArea();
calculatePerimeter();
}
private void calculateArea() {
double s = (side1 + side2 + side3) / 2;
area = Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
private void calculatePerimeter() {
perimeter = side1 + side2 + side3;
}
public void displayInfo() {
System.out.println("Triangle:\nSide1: " + side1 + "\nSide2: " + side2 + "\nSide3: " + side3 + "\nArea: " + area + "\nPerimeter: " + perimeter);
}
}
// Circle类
public class Circle {
private double radius;
private double area;
private double perimeter;
public Circle(double radius) {
this.radius = radius;
calculateArea();
calculatePerimeter();
}
private void calculateArea() {
area = Math.PI * radius * radius;
}
private void calculatePerimeter() {
perimeter = 2 * Math.PI * radius;
}
public void displayInfo() {
System.out.println("Circle:\nRadius: " + radius + "\nArea: " + area + "\nPerimeter: " + perimeter);
}
}
// 主类
public class Main {
public static void main(String[] args) {
Triangle triangle = new Triangle(3, 4, 5);
triangle.displayInfo();
Circle circle = new Circle(5);
circle.displayInfo();
}
}
```
输出结果为:
```
Triangle:
Side1: 3.0
Side2: 4.0
Side3: 5.0
Area: 6.0
Perimeter: 12.0
Circle:
Radius: 5.0
Area: 78.53981633974483
Perimeter: 31.41592653589793
```
阅读全文