java 三角形类Triangle,属性:三条边,构造函数(2个),一组Set方法,一组get方法
java三角形类Triangle,属性:三条边,构造函数(2个),一组Set方法,一组get方法,从键盘输入三条边side,计算面积area,计算周长perimeter,...
java 三角形类Triangle,属性:三条边,构造函数(2个),一组Set方法,一组get方法,从键盘输入三条边side,计算面积area,计算周长perimeter,判断三角形形状(三角形是等边、等腰还是普通三角形),输出三角形详细信息的方法。测试类TestTriangle,创建对象,调用各个方法。
展开
2个回答
展开全部
public class Triangle {
private double a;
private double b;
private double c;
public Triangle() {
super();
}
public Triangle(double a, double b, double c) {
super();
this.a = a;
this.b = b;
this.c = c;
}
public double getA() {
return a;
}
public void setA(double a) {
this.a = a;
}
public double getB() {
return b;
}
public void setB(double b) {
this.b = b;
}
public double getC() {
return c;
}
public void setC(double c) {
this.c = c;
}
public double area() {
double p = (a + b + c) / 2;
return (double) Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
public double perimeter() {
return a + b + c;
}
public String shape() {
if (a == b && a == c) {
return "等边三角形";
} else if (a == b || a == c || b == c) {
return "等腰三角形";
} else {
return "普通三角形";
}
}
public void printDetailInfo() {
System.out.printf("三角形三条边为:%f, %f, %f。面积为:%f。周长为:%f。形状为:%s。\n", a, b, c,
area(), perimeter(), shape());
}
}
import java.util.Scanner;
public class TestTriangle {
public static void main(String[] args) {
System.out.println("请输入三角形三条边的长度:");
Scanner scanner = new Scanner(System.in);
double a = scanner.nextDouble();
double b = scanner.nextDouble();
double c = scanner.nextDouble();
scanner.close();
if (!isTriangle(a, b, c)) {
System.out.println("不能构成三角形。");
return;
}
Triangle triangle = new Triangle(a, b, c);
System.out.printf("三角形面积为:%f。\n", triangle.area());
System.out.printf("三角形周长为:%f。\n", triangle.perimeter());
System.out.printf("三角形形状为:%s。\n", triangle.shape());
triangle.printDetailInfo();
}
private static boolean isTriangle(double a, double b, double c) {
return a + b <= c || a + c <= b || b + c <= a ? false : true;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询