用java编程序,创建一个描述三角形的类Triangle,类中有三边长、面积、周长等成员变量,有带参数的构造方法,以及计算面积、计算周长和输出信息等成员方法,再创建描述圆形的类Circle,其中有半径、面积、周长等属性,有带参数的构造方法,以及计算面积、计算周长和输出信息等成员方法,在主类中测试三角形类和圆形类的使用(创建对象,计算面积、周长,输出信息)
时间: 2023-05-17 10:02:55 浏览: 77
好的,以下是用Java编写的Triangle和Circle类的代码:
Triangle类:
```
public class Triangle {
private double side1;
private double side2;
private double side3;
private double area;
private double perimeter;
public Triangle(double s1, double s2, double s3) {
side1 = s1;
side2 = s2;
side3 = s3;
double s = (s1 + s2 + s3) / 2;
area = Math.sqrt(s * (s - s1) * (s - s2) * (s - s3));
perimeter = s1 + s2 + s3;
}
public double getArea() {
return area;
}
public double getPerimeter() {
return perimeter;
}
public void printInfo() {
System.out.println("Triangle with sides " + side1 + ", " + side2 + ", " + side3);
System.out.println("Area: " + area);
System.out.println("Perimeter: " + perimeter);
}
}
```
Circle类:
```
public class Circle {
private double radius;
private double area;
private double circumference;
public Circle(double r) {
radius = r;
area = Math.PI * r * r;
circumference = 2 * Math.PI * r;
}
public double getArea() {
return area;
}
public double getCircumference() {
return circumference;
}
public void printInfo() {
System.out.println("Circle with radius " + radius);
System.out.println("Area: " + area);
System.out.println("Circumference: " + circumference);
}
}
```
在主类中测试Triangle和Circle类的使用:
```
public class Main {
public static void main(String[] args) {
Triangle t = new Triangle(3, 4, 5);
t.printInfo();
Circle c = new Circle(2.5);
c.printInfo();
}
}
```
输出结果:
```
Triangle with sides 3.0, 4.0, 5.0
Area: 6.0
Perimeter: 12.0
Circle with radius 2.5
Area: 19.634954084936208
Circumference: 15.707963267948966
```
阅读全文