0709--第六章3题

代码需求:判断三个数是否能组成三角形以及组成的三角形类型

判断是否能组成三角形代码:

/**
 * @author Mr.Wang
 * 判断输入的三个数是否符合三角形边长关系
 * 合法返回true,不合法返回false
 *
 */
public class isTriangle {
    public boolean isTriangle(int a,int b,int c) {
        boolean flag=false;
        if(a<b+c&&b<a+c&&c<a+b) {
            flag = true;
        }else {
            
        }
        return flag;
    }
    
}

判断组成的三角形类型代码:

/**
 * @author Mr.Wang
 * 判断构成的三角形属于什么类型的三角形
 * 返回三角形的类型
 *
 */
public class Shape {
    public String shape(int a,int b,int c) {
        String shape = ">>>>";
        if((a^2) == (b^2+c^2)||(b^2) == (a^2+c^2)||(c^2) == (a^2+b^2)) {
            shape = "这是一个直角三角形。";
        }else if((a^2) > (b^2+c^2)||(b^2) > (a^2+c^2)||(c^2) > (a^2+b^2)) {
            shape = "这是一个钝角三角形。";
        }else {
            shape = "这是一个锐角三角形。";
        }
        return shape;
    }
    
    
}

测试类:

/**
 * @author Mr.Wang
 * 测试类:
 * 用户输入三角形三条边
 * 调用方法判断是否符合三角形规则以及判别组成的三角形类型
 *
 */
public class Test {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String choose = null;
        isTriangle flag = new isTriangle();
        Shape sp = new Shape();
        do{            
            System.out.print("请输入第一条边:");
            int a = input.nextInt();
            System.out.print("请输入第二条边:");
            int b = input.nextInt();
            System.out.print("请输入第三条边:");
            int c = input.nextInt();
            
            boolean flag1 = flag.isTriangle(a, b, c);
            if(flag1 ==true) {
                String shape =sp.shape(a, b, c);
                System.out.println(shape);
            }else {
                System.out.println("这不能构成三角形。");
            }
            System.out.print("继续吗?(y/n):");
            choose = input.next();
        }while(choose.equals("y"));
        
    }
}

测试运行结果:

猜你喜欢

转载自www.cnblogs.com/Dean-0/p/11164128.html