用Java生成三角形,圆,矩形的面积和周长
时间: 2024-05-01 14:17:52 浏览: 77
java程序代码实现矩形、三角形、圆的面积和周长计算
4星 · 用户满意度95%
Sure, 我可以回答你的问题。
下面是 Java 生成三角形,圆,矩形的面积和周长的示例代码。
Triangle.java:
```java
public class Triangle {
private double base;
private double height;
private double side1;
private double side2;
private double side3;
public Triangle(double base, double height, double side1, double side2, double side3) {
this.base = base;
this.height = height;
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
public double getArea() {
return 0.5 * base * height;
}
public double getPerimeter() {
return side1 + side2 + side3;
}
}
```
Circle.java:
```java
public class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
public double getPerimeter() {
return 2 * Math.PI * radius;
}
}
```
Rectangle.java:
```java
public class Rectangle {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
}
```
你可以在你的应用程序中创建这些类的实例,然后使用它们的方法来获取它们的面积和周长,如下所示:
```java
Triangle triangle = new Triangle(3, 4, 5, 4, 3);
double triangleArea = triangle.getArea();
double trianglePerimeter = triangle.getPerimeter();
Circle circle = new Circle(2);
double circleArea = circle.getArea();
double circlePerimeter = circle.getPerimeter();
Rectangle rectangle = new Rectangle(6, 9);
double rectangleArea = rectangle.getArea();
double rectanglePerimeter = rectangle.getPerimeter();
```
Hope that helps!
阅读全文