编写三角形类,实现三角形面积和周长计算等功能。 要求: (1)三个属性 (2)两个构造方法和全部getter和setter (3)三个自定义的方法:面积、周长、是否是直角三角形。 (4)单独编写测试类,测试类的全部功能。用java编写
时间: 2024-01-17 19:05:53 浏览: 70
好的,以下是你想要的程序代码:
Triangle.java
```java
public class Triangle {
private double a, b, c;
public Triangle() {
}
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
public double getA() {
return a;
}
public void setA(double a) {
this.a = a;
}
public double getB() {
return b;
}
public void setB(double b) {
this.b = b;
}
public double getC() {
return c;
}
public void setC(double c) {
this.c = c;
}
public double getArea() {
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
public double getPerimeter() {
return a + b + c;
}
public boolean isRightTriangle() {
if (a * a + b * b == c * c || a * a + c * c == b * b || b * b + c * c == a * a) {
return true;
} else {
return false;
}
}
}
```
TestTriangle.java
```java
import java.util.Scanner;
public class TestTriangle {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入三角形的三条边长: ");
double a = scanner.nextDouble();
double b = scanner.nextDouble();
double c = scanner.nextDouble();
Triangle triangle = new Triangle(a, b, c);
System.out.println("面积为:" + triangle.getArea());
System.out.println("周长为:" + triangle.getPerimeter());
if (triangle.isRightTriangle()) {
System.out.println("这是个直角三角形");
} else {
System.out.println("这不是个直角三角形");
}
}
}
```
在测试类中,我们通过Scanner类获取用户输入的三角形三个边长,然后创建Triangle对象,并调用对象的方法计算三角形的面积、周长和是否是直角三角形,最终输出结果。
阅读全文