需求:给出三角形的三边长,判断是否三角形,如是,判断是等边三角形,等腰三角形,不等边三角形,锐角三角形,直角三角形和钝角三角形,并计算出三角形的面积.

考查点:建模的准确性,思维的全面性,浮点数的比较.

补充知识:cosA
=b方+c方-a方/2*b*c
package com.sitinspring;


/** *//**
* 形状类,未必是三角形
* @author sitinspring(junglesong@gmail.com)
*
* @date 2007-11-6
*/

public class Shape
{
// 三边长
protected double a;
protected double b;
protected double c;

public Shape(double a,double b,double c)
{
this.a=a;
this.b=b;
this.c=c;
}

protected String getInfo()
{
return "("+a+","+b+","+c+")";
}

public String toString()
{
return getInfo()+"非三角形";
}
}

package com.sitinspring;



/** *//**
* 三角形类
* @author sitinspring(junglesong@gmail.com)
*
* @date 2007-11-6
*/

public class Triangle extends Shape
{
// 三角
private double cosA;
private double cosB;
private double cosC;
private static final double Mini=0.000001;

public Triangle(double a,double b,double c)
{
super(a,b,c);
cosA=getCos(a,b,c);
cosB=getCos(b,a,c);
cosC=getCos(c,a,b);
}

private static double getCos(double a,double b,double c)
{
return (b*b+c*c-a*a)/(2*b*c);
}

private static boolean isEqual(double op1,double op2)
{
return Math.abs(op1-op2)<Mini;
}

public String toString()
{
String retval=getInfo()+"三角形";
// 边判断

if(isEqual(a,b) && isEqual(b,c))
{
retval+=" 等边三角形";
}

else if(isEqual(a,b) || isEqual(b,c))
{
retval+=" 等腰三角形";
}

else
{
retval+=" 常规三角形";
}
// 角判断

if(cosA<0 || cosB<0 || cosC<0)
{
retval+=" 钝角三角形";
}

else if(isEqual(cosA,0) || isEqual(cosB,0) || isEqual(cosC,0))
{
retval+=" 直角三角形";
}

else
{
retval+=" 锐角三角形";
}
return retval;
}
}

package com.sitinspring;


/** *//**
* 形状构造器
* @author sitinspring(junglesong@gmail.com)
*
* @date 2007-11-6
*/

public class ShapeMaker
{

public Shape generate(double a,double b,double c)
{

if(a<0 || b<0 || c<0)
{
return new Shape(a,b,c);
}

else if(a+b<c || a+c<b || b+c<a)
{
return new Shape(a,b,c);
}
return new Triangle(a,b,c);
}

public static void main(String[] args)
{
ShapeMaker maker=new ShapeMaker();
System.out.println(maker.generate(1, 1, 3));
System.out.println(maker.generate(3, 3, 3));
System.out.println(maker.generate(3, 3, 4));
System.out.println(maker.generate(3, 4, 2));
System.out.println(maker.generate(1, 1, -3));
System.out.println(maker.generate(3, 4, 3));
System.out.println(maker.generate(3, 4, 4));
System.out.println(maker.generate(3, 4, 5));
System.out.println(maker.generate(3, 4, 6));
}
}

代码下载:
http://www.blogjava.net/Files/sitinspring/TriAngle20071106135459.rar