例子很简单,设计一个程序,输入三个整数,判断这三个整数作为三边的长度能否构成一个三角形,如果可以则返回三角形的类型(普通三角形,等腰三角形或者等边三角形)
实现代码(我自己随便写的做个例子用,估计代码质量很差。。):
public class JudgeTriangle
{
//普通三角形
private static int NORMAL_TRIANGLE = 0;
//等腰三角形
private static int ISOSCELES_TRIANGLE = 1;
//等边三角形
private static int EQUILATERAL_TRIANGEL = 2;
//无法构成三角形
private static int ERROR_CODE = -1;
public int getNormalTriangle()
{
return NORMAL_TRIANGLE;
}
public int getIsoscelesTriangle()
{
return ISOSCELES_TRIANGLE;
}
public int getEquilateralTriangle()
{
return EQUILATERAL_TRIANGEL;
}
public int getErrorCode()
{
return ERROR_CODE;
}
public int judgeType(int a,int b,int c)
{
if ((a<=0)||(b<=0)||(c<=0))
{
return ERROR_CODE;
}
if ((a+b<c || Math.abs(a-b)>c) || (b+c<a || Math.abs(b-c)>a) || (a+c<b || Math.abs(a-c)>b))
{
return ERROR_CODE;
}
if (a==b || b==c || c==a)
{
if (a==b && b==c)
{
return EQUILATERAL_TRIANGEL;
}
else
{
return ISOSCELES_TRIANGLE;
}
}
else
{
return NORMAL_TRIANGLE;
}
}
}
单元测试代码:
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class JudgeTriangleTest {
private static JudgeTriangle judgeTriangle = new JudgeTriangle();
@Before
public void setUp() throws Exception {
}
@Test
public void testIsNormalTriangle() throws Exception {
assertEquals(judgeTriangle.getNormalTriangle(),judgeTriangle.judgeType(3, 4, 5));
}
@Test
public void testIsIsoscelesTriangle() throws Exception {
assertEquals(judgeTriangle.getIsoscelesTriangle(),judgeTriangle.judgeType(2, 2, 3));
}
@Test
public void testEquilateralTriangle() throws Exception {
assertEquals(judgeTriangle.getEquilateralTriangle(),judgeTriangle.judgeType(2, 2, 2));
}
@Test
public void testNotTriangle() throws Exception {
assertEquals(judgeTriangle.getErrorCode(),judgeTriangle.judgeType(10, -10, 10));
assertEquals(judgeTriangle.getErrorCode(),judgeTriangle.judgeType(10, 2, 2));
}
@After
public void tearDown() throws Exception {
}
}