JAVA如何编写程序判断一个三角形是否为等腰三角形
1个回答
展开全部
package demo;
import java.util.Scanner;
public class Triangle
{
/**
* 等腰
*/
public static final int ISOSCELES = 1;
/**
* 等边
*/
public static final int EQUILATERAL = 2;
/**
* 直角
*/
public static final int RIGHTANGLE = 4;
/**
* 普通
*/
public static final int GENERAL = 6;
/**
* 不构成三角形
*/
public static final int NOTHING = 7;
double a;
double b;
double c;
public Triangle ( double a, double b, double c )
{
this.a = a;
this.b = b;
this.c = c;
}
public static int isWhichOne ( Triangle triangle )
{
double a = triangle.a;
double b = triangle.b;
double c = triangle.c;
if (a + b > c && a + c > b && b + c > a && Math.abs (a - b) < c && Math.abs (a - c) < b && Math.abs (b - c) < a)
{
if (a == b && a == c)
{
return Triangle.EQUILATERAL | Triangle.ISOSCELES;
}
else if (a * a + b * b == c * c || a * a + c * c == b * b || c * c + b * b == a * a)
{
if (a == b || a == c || b == c)
{
return Triangle.RIGHTANGLE | Triangle.ISOSCELES;
}
return Triangle.RIGHTANGLE;
}
else if (a == b || a == c || b == c)
{
return Triangle.ISOSCELES;
}
else
{
return Triangle.GENERAL;
}
}
else
{
return Triangle.NOTHING;
}
}
public static double perimeter ( Triangle triangle )
{
return triangle.a + triangle.b + triangle.c;
}
public static double area ( Triangle triangle )
{
double a = triangle.a;
double b = triangle.b;
double c = triangle.c;
return 1.d / 4 * Math.sqrt (( a + b + c ) * ( a + b - c ) * ( a + c - b ) * ( b + c - a ));
}
public static void translate ( Triangle triangle )
{
int type = isWhichOne (triangle);
switch (type)
{
case Triangle.ISOSCELES:
System.out.println ("等腰三角形");
break;
case ( Triangle.EQUILATERAL | Triangle.ISOSCELES ):
System.out.println ("等边三角形 + 等腰三角形");
break;
case Triangle.GENERAL:
System.out.println ("普通三角形");
break;
case ( Triangle.RIGHTANGLE | Triangle.ISOSCELES ):
System.out.println ("直角三角形 + 等腰三角形");
break;
case Triangle.RIGHTANGLE:
System.out.println ("直角三角形");
break;
default:
System.out.println ("不构成三角形");
break;
}
if (type != Triangle.NOTHING)
{
System.out.println ("周长是:" + perimeter (triangle));
System.out.println ("面积是:" + area (triangle));
}
}
public static void main ( String[] args )
{
System.out.println ("输入构成三角形的三边长:(空格隔开)\n退出按 (n/N), 否则继续: ");
String error = "输入有误,请重新输入: ";
String reg = "^\\d+\\s+\\d+\\s+\\d+$";
Scanner scanner = new Scanner (System.in);
while (scanner.hasNextLine ())
{
String line = scanner.nextLine ().trim ();
if ("n".equalsIgnoreCase (line))
{
break;
}
if (!line.matches (reg))
{
System.err.println (error);
}
else
{
try
{
String[] input = line.split ("\\s+");
int a = Integer.parseInt (input[0]);
int b = Integer.parseInt (input[1]);
int c = Integer.parseInt (input[2]);
Triangle triangle = new Triangle (a, b, c);
translate (triangle);
}
catch (NumberFormatException e)
{
System.err.println (error);
}
System.out.println ("退出按 (n/N), 否则继续: ");
}
}
scanner.close ();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询