- import java.util.ArrayList;
- import java.util.List;
- public class TriangleWithException {
- private double side1, side2, side3;
- private static int numberOfObjects = 0;
- public TriangleWithException() {
- this(1.0, 1.0, 1.5);
- }
- public TriangleWithException(double newside1, double newside2,
- double newside3) {
- setSide(newside1, newside2, newside3);
- numberOfObjects++;
- }
- public double getSide1() {
- return side1;
- }
- public double getSide2() {
- return side2;
- }
- public double getSide3() {
- return side3;
- }
- public void setSide(double newSide1, double newSide2, double newSide3)
- throws IllegalArgumentException {
- if (newSide1 >= 0 && newSide2 >= 0 && newSide3 >= 0
- && (newSide1 + newSide2 > newSide3)
- && (newSide1 + newSide3 > newSide2)
- && (newSide2 + newSide3 > newSide1)) {
- side1 = newSide1;
- side2 = newSide2;
- side3 = newSide3;
- } else
- throw new IllegalArgumentException("Side cannot be negative");
- }
- public static int getNumberOfObjects() {
- return numberOfObjects;
- }
- public double findArea() {
- double p = (side1 + side2 + side3) / 2;
- double s = Math.sqrt((double) (p * (p - side1) * (p - side2) * (p - side3)));
- return s;
- }
- public static void main(String args[]){
- List<TriangleWithException> list=new ArrayList<TriangleWithException>();
- list.add(new TriangleWithException(2,2,3));
- list.add(new TriangleWithException(3,2,4));
- list.add(new TriangleWithException(2,4,5));
- list.add(new TriangleWithException(3,5,7));
-
- for(TriangleWithException tr:list){
- System.out.println("面积是:"+tr.findArea());
- }
-
- }
- }
复制代码 上面的main方法就是按照你的需求做的! |