用Java 编写一个三角形类,要求能够计算三角形的面积和周长。从键盘输入一个三角形的3条边的长度,并用这3条边创建一个三角形对象,输出此三角形对象的面积和周长。
时间: 2024-05-09 18:18:42 浏览: 29
计算三角形的面积和周长(java)
5星 · 资源好评率100%
```java
import java.util.Scanner;
public class Triangle {
private double a;
private double b;
private double c;
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
public double getArea() {
double p = getPerimeter() / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
public double getPerimeter() {
return a + b + c;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入三角形的边长a:");
double a = scanner.nextDouble();
System.out.print("请输入三角形的边长b:");
double b = scanner.nextDouble();
System.out.print("请输入三角形的边长c:");
double c = scanner.nextDouble();
Triangle triangle = new Triangle(a, b, c);
System.out.println("三角形的面积为:" + triangle.getArea());
System.out.println("三角形的周长为:" + triangle.getPerimeter());
}
}
```
阅读全文