*12.5 (IllegalTriangleException) Programming Exercise 11.1 defined the
Triangle class with three sides. In a triangle, the sum of any two sides is
greater than the other side. The Triangle class must adhere to this rule.
Create the IllegalTriangleException class, and modify the constructor
of the Triangle class to throw an IllegalTriangleException object if a
triangle is created with sides that violate the rule, as follows:
/** Construct a triangle with the specified sides */
public Triangle(double side1, double side2, double side3)
throws IllegalTriangleException {
// Implement it }
*12.5(IllegalTriangleException)编程练习11.1定义了三边三角形类。在三角形中,任意两条边的和为大于另一侧。三角形类必须遵守此规则。
创建IllegalTriangleException类,并修改构造函数
如果三角形是用违反规则的边创建的,如下所示:
/** Construct a triangle with the specified sides */
public Triangle(double side1, double side2, double side3)
throws IllegalTriangleException {
// Implement it }
代码如下:
import java.util.Scanner;
public class Unite12Test5
{
public static void main(String[] args)
{
try {
Triangle t = new Triangle(1,2,1);
} catch (IllegalTriangleException e) {
System.out.println(e);
}
}
}
class Triangle extends SimpleGeometricObject
{
double side1=1.0;
double side2=1.0;
double side3=1.0;
public Triangle()
{
}
public double getSide1() {
return side1;
}
public void setSide1(double side1) {
this.side1 = side1;
}
public double getSide2() {
return side2;
}
public void setSide2(double side2) {
this.side2 = side2;
}
public double getSide3() {
return side3;
}
public void setSide3(double side3) {
this.side3 = side3;
}
public Triangle(double side1,double side2,double side3)
throws IllegalTriangleException
{
this.side1=side1;
this.side2=side2;
this.side3=side3;
if(side1+side2<=side3||side1+side3<=side2||side3+side2<=side1)
{
throw new IllegalTriangleException("该三角形错误");
}
}
public double getArea()
{
double s = (this.side1+this.side2+this.side3)/2;
return Math.sqrt(s*(s-this.side1)*(s-this.side2)*(s-this.side3));
}
public double getPerimrter()
{
return this.side1+this.side2+this.side3;
}
public String toString()
{
return "Triangel: side1:"+side1+" side2 = "+side2+" side3 = "+side3;
}
}
class IllegalTriangleException extends Exception
{
String message ;
public IllegalTriangleException()
{
message = "该三角形错误";
}
public IllegalTriangleException(String argu){
message = argu;
}
@Override
public String toString(){
return message;
}
}
结果如下: