/**
* @author huazie
* @version 2.0.0
* @since 2.0.0
*/
public class Triangle {
private double side1;
private double side2;
private double side3;
public void setAll(double side1, double side2, double side3) throws Exception{
if (side1 < 0 || side2 < 0 || side3 < 0) {
throw new Exception("边长必须为正数");
}
if (side1 + side2 < side3 || side1 + side3 < side2 || side2 + side3 < side1) {
throw new Exception("三条边长必须能组合成三角形(三角形任意两边和大于第三边)");
}
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
public void print() {
if (side1 > 0 && side2 > 0 && side3 > 0)
System.out.print("三角形三边长分别为 " + side1 + "," + side2 + "," + side3);
}
public static void main(String[] args) throws Exception {
Triangle t = new Triangle();
t.setAll(3.0, 4.0, 5.0);
t.print();
}
}
创建三角形类
public class triangle {
private double a;
private double b;
private double c;
public triangle(double a, double b, double c) {
if (a <= 0 || b <= 0 || c <= 0) {
throw new illegalargumentexception("triangle side length should be positive");
}
if (a + b <= c || a + c <= b || b + c <= a) {
throw new illegalargumentexception("not a triangle");
}
this.a = a;
this.b = b;
this.c = c;
}
public void seta(double a) {
if (a <= 0) {
throw new illegalargumentexception("triangle side length should be positive");
}
if (a + b <= c || a + c <= b || b + c <= a) {
throw new illegalargumentexception("not a triangle");
}
this.a = a;
}
public void setb(double b) {
if (b <= 0) {
throw new illegalargumentexception("triangle side length should be positive");
}
if (a + b <= c || a + c <= b || b + c <= a) {
throw new illegalargumentexception("not a triangle");
}
this.b = b;
}
public void setc(double c) {
if (c <= 0) {
throw new illegalargumentexception("triangle side length should be positive");
}
if (a + b <= c || a + c <= b || b + c <= a) {
throw new illegalargumentexception("not a triangle");
}
this.c = c;
}
public void printsides() {
system.out.println("triangle sides: " + a + ", " + b + ", " + c);
}
}
主函数调用例
public class main {
public static void main(string[] args) {
triangle triangle = new triangle(3, 4, 5);
triangle.printsides();
triangle.seta(2);
triangle.printsides();
}
}