创建一个Triangle类,根据输入的三边判断能否构成等边三角形、等腰三角形、一般三角形,并用JUnit进行单元测试并用JUnit进行单元测试
时间: 2024-03-06 18:46:36 浏览: 99
好的,我可以帮您解答这个问题。首先,我们可以创建一个Triangle类,如下所示:
```java
public class Triangle {
private double side1;
private double side2;
private double side3;
public Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
public boolean isEquilateral() {
return side1 == side2 && side2 == side3;
}
public boolean isIsosceles() {
return side1 == side2 || side1 == side3 || side2 == side3;
}
public boolean isScalene() {
return side1 != side2 && side1 != side3 && side2 != side3;
}
public boolean isTriangle() {
return side1 + side2 > side3 && side1 + side3 > side2 && side2 + side3 > side1;
}
}
```
然后,我们可以使用JUnit进行单元测试。下面是一个示例:
```java
import static org.junit.Assert.*;
import org.junit.Test;
public class TriangleTest {
@Test
public void testIsEquilateral() {
Triangle triangle1 = new Triangle(3, 3, 3);
assertTrue(triangle1.isEquilateral());
Triangle triangle2 = new Triangle(2, 2, 3);
assertFalse(triangle2.isEquilateral());
}
@Test
public void testIsIsosceles() {
Triangle triangle1 = new Triangle(3, 3, 4);
assertTrue(triangle1.isIsosceles());
Triangle triangle2 = new Triangle(3, 4, 5);
assertFalse(triangle2.isIsosceles());
}
@Test
public void testIsScalene() {
Triangle triangle1 = new Triangle(3, 4, 5);
assertTrue(triangle1.isScalene());
Triangle triangle2 = new Triangle(2, 3, 4);
assertFalse(triangle2.isScalene());
}
@Test
public void testIsTriangle() {
Triangle triangle1 = new Triangle(3, 4, 5);
assertTrue(triangle1.isTriangle());
Triangle triangle2 = new Triangle(2, 3, 6);
assertFalse(triangle2.isTriangle());
}
}
```
在这个示例中,我们使用了`assertTrue`和`assertFalse`来断言`isEquilateral`、`isIsosceles`、`isScalene`和`isTriangle`方法的返回值是否符合预期。
阅读全文