获取无法构造的对象数

hof1towb  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(279)

对于我的一个类赋值,我需要创建一个创建三角形对象的类。根据几何规则,对于一个有效的三角形,任意一条边的长度应小于其他两条边的长度之和。我编写的对象构造函数类可以采用任何double,这意味着可以输入三角形的一侧,其长度比其他两个的组合长度长。这违反了三角形的几何规则(这是可以的)。但是,我想记录有多少三角形违反了几何规则,因此无法构造。
通常,您会使用try,catch块来捕获异常。但是,这里的问题是,一旦到达异常,就会跳过异常后面的对象,而不会创建它。这就产生了两个问题:第一,非法对象之后的任何合法对象都不会被创建。第二,我无法跟踪除了第一个非法对象之外有多少对象未能创建(因为其余对象被跳过)。如何重新构造代码,以便创建合法对象(即使碰到非法对象),并统计有多少合法/非法对象?我已经使用了一个定制的异常处理程序对象,我已经为三角形对象编写了这个对象,但是为了减少代码,这里没有包括它。我是一个初学者,所以对你来说显而易见的解决方案对我来说是模糊的。谢谢你的帮助。
这是我的三角测试仪代码:

public class TestTriangle {

    public static void main(String[] args) throws IllegalTriangleException {
        // Start of try block for creating 4 triangle objects
        try {

            Triangle triangle1 = new Triangle();            // create first triangle using default constructor
            System.out.println(triangle1.toString());       // output the information about length of sides
            // output info about perimeter and area of triangle
            System.out.println("The perimeter of the triangle1 is " + triangle1.getPerimeter()); 
            System.out.println("The area of the triangle1 is " + triangle1.getArea());           
            System.out.println();

            Triangle triangle2 = new Triangle(3, 4, 5);     // create a second triangle given sides
            System.out.println(triangle2.toString());
            System.out.println("The perimeter of the triangle2 is " + triangle2.getPerimeter());
            System.out.println("The area of the triangle2 is " + triangle2.getArea());
            System.out.println();

            Triangle triangle3 = new Triangle(4, 2, 5);     // create a third triangle given sides
            System.out.println(triangle3.toString());
            System.out.println("The perimeter of the triangle3 is " + triangle3.getPerimeter());
            System.out.println("The area of the triangle3 is " + triangle3.getArea());
            System.out.println();

            Triangle triangle4 = new Triangle(2, 3, 7);     // try to create an illegal triangle
            System.out.println(triangle4.toString());
            System.out.println("The perimeter of the triangle4 is " + triangle4.getPerimeter());
            System.out.println("The area of the triangle4 is " + triangle4.getArea());
            System.out.println();

            Triangle triangle5 = new Triangle(2, 4, 9);     // try to create an illegal triangle
            System.out.println(triangle5.toString());
            System.out.println("The perimeter of the triangle5 is " + triangle5.getPerimeter());
            System.out.println("The area of the triangle5 is " + triangle5.getArea());
            System.out.println();

        // catch exceptions, if any 
        } catch (IllegalTriangleException ex) {
            System.out.println("Exception: " + ex);
        }
        System.out.println();
        System.out.println(Triangle.getNumberOfObjects() + " triangles constructed");
        System.out.println(Triangle.illegalAttempts() + " triangle(s) failed to construct");        
    }
}

如果你需要研究的话,这里有一个类构造函数:

public class Triangle {

    // declare variables for each side of the triangle
    private double side1;
    private double side2;
    private double side3;

    // declare variables to keep track of number of objects created or illegal attempts
    private static int numberOfObjects = 0;
    private static int illegalAttempts = 0;

    // default constructor for triangle
    public Triangle() {
        side1 = 1.0;
        side2 = 1.0;
        side3 = 1.0;
        numberOfObjects++;
    }

    // constructor for creating triangles based on length of sides
    public Triangle(double newSide1, double newSide2, double newSide3) throws IllegalTriangleException {
        setSides (newSide1, newSide2, newSide3);

        numberOfObjects++;
    }

    // setter for creating triangles given the length of sides
    public void setSides (double newSide1, double newSide2, double newSide3) throws IllegalTriangleException {
        // According to geometric rules, in triangles, any one side should be shorter than the combined length of other two. 
        // Check to see if any one side is longer than the combined length of other two. If so, throw the designed exception.

        if (newSide1 >= newSide2 + newSide3) { 
            illegalAttempts++;
            throw new IllegalTriangleException(newSide1, newSide2, newSide3);

        } else if (newSide2 >= newSide1 + newSide3) {
            illegalAttempts++;
            throw new IllegalTriangleException(newSide2, newSide1, newSide3);

        } else if (newSide3 >= newSide1 + newSide2) {
            illegalAttempts++;
            throw new IllegalTriangleException(newSide3, newSide1, newSide2);
        } else {

            side1 = newSide1;       // In case the geometric rule is not violated, create the sides. 
            side2 = newSide2;
            side3 = newSide3;
        }       
    }
    // constructor for getting the number triangle created
    public static int getNumberOfObjects() {
        return numberOfObjects;
    }

    public static int illegalAttempts() {
        return illegalAttempts;
    }
    // constructor for calculating the perimeter of triangles 
    public double getPerimeter() {
        return side1 + side2 + side3;
    }
    // constructor for calculating the area of a triangle given three sides: sqrt(p*(p-a)*(p-b)*(p-c))
    public double getArea() {
        double perimeter = side1 + side2 + side3;
        return Math.sqrt(perimeter * (perimeter - side1) * (perimeter - side2) * (perimeter - side3));
    }

    // create an string object giving information about the triangle
    public String toString() {
         return "Triangle: Side a = " + side1 + ", Side b = " + side2
                 + ", Side c = " + side3;
    }

}

代码的输出应该是这样的:
三角形:边a=4.0,边b=2.0,边c=5.0三角形3的周长为11.0三角形3的面积为64.48255578061404
例外:非法三角形例外:非法三角形,任意两边之和小于另一边的边1是7.0边2是2.0边3是3.0
构造了3个三角形2个三角形未能构造

pb3s4cty

pb3s4cty1#

考虑到三角形初始化除了它们的值之外是相同的,一个选项可能是从try块中提取硬编码的值。如果任何一个三角形构造失败,它将被捕获、处理,然后转到下一个三角形参数集。

public class TestTriangle {

    public static void main(String[] args) throws IllegalTriangleException {
        Triangle triangle1 = new Triangle();            // create first triangle using default constructor
        System.out.println(triangle1.toString());       // output the information about length of sides
        // output info about perimeter and area of triangle
        System.out.println("The perimeter of the triangle1 is " + triangle1.getPerimeter());
        System.out.println("The area of the triangle1 is " + triangle1.getArea());
        System.out.println();

        List<List<Integer>> triangleEdgeLengths = new ArrayList<>();
        triangleEdgeLengths.add(Arrays.asList(3, 4, 5));
        triangleEdgeLengths.add(Arrays.asList(4, 2, 5));
        triangleEdgeLengths.add(Arrays.asList(2, 3, 7));
        triangleEdgeLengths.add(Arrays.asList(2, 4, 9));

        triangleEdgeLengths.forEach((edgeLengths) -> {
            try {
                Triangle triangle = new Triangle(edgeLengths.get(0), edgeLengths.get(1), edgeLengths.get(2));
                System.out.println(triangle.toString());
                System.out.println("The perimeter of the triangle is " + triangle.getPerimeter());
                System.out.println("The area of the triangle is " + triangle.getArea());
                System.out.println();
                // catch exceptions, if any
            } catch (IllegalTriangleException ex) {
                System.out.println("Exception: " + ex);
            }
        });

        System.out.println();
        System.out.println(Triangle.getNumberOfObjects() + " triangles constructed");
        System.out.println(Triangle.illegalAttempts() + " triangle(s) failed to construct");
    }
}

输出

Triangle: Side a = 1.0, Side b = 1.0, Side c = 1.0
The perimeter of the triangle1 is 3.0
The area of the triangle1 is 4.898979485566356

Triangle: Side a = 3.0, Side b = 4.0, Side c = 5.0
The perimeter of the triangle is 12.0
The area of the triangle is 77.76888838089432

Triangle: Side a = 4.0, Side b = 2.0, Side c = 5.0
The perimeter of the triangle is 11.0
The area of the triangle is 64.48255578061404

Exception: IllegalTriangleException
Exception: IllegalTriangleException

3 triangles constructed
2 triangle(s) failed to construct

Process finished with exit code 0

twicelost请求了一个避免使用列表的选项。一个稍微冗长的选项是将每个三角形构造 Package 在try/catch中。

public static void main(String[] args) throws IllegalTriangleException {
        Triangle triangle1 = new Triangle();            // create first triangle using default constructor
        System.out.println(triangle1.toString());       // output the information about length of sides
        // output info about perimeter and area of triangle
        System.out.println("The perimeter of the triangle1 is " + triangle1.getPerimeter());
        System.out.println("The area of the triangle1 is " + triangle1.getArea());
        System.out.println();

        try {
            Triangle triangle2 = new Triangle(3, 4, 5);     // create a second triangle given sides
            System.out.println(triangle2.toString());
            System.out.println("The perimeter of the triangle2 is " + triangle2.getPerimeter());
            System.out.println("The area of the triangle2 is " + triangle2.getArea());
            System.out.println();
        } catch (IllegalTriangleException ex) {
            System.out.println("Exception: " + ex);
        }

        try {
            Triangle triangle3 = new Triangle(4, 2, 5);     // create a third triangle given sides
            System.out.println(triangle3.toString());
            System.out.println("The perimeter of the triangle3 is " + triangle3.getPerimeter());
            System.out.println("The area of the triangle3 is " + triangle3.getArea());
            System.out.println();
        } catch (IllegalTriangleException ex) {
            System.out.println("Exception: " + ex);
        }

        try {
            Triangle triangle4 = new Triangle(2, 3, 7);     // try to create an illegal triangle
            System.out.println(triangle4.toString());
            System.out.println("The perimeter of the triangle4 is " + triangle4.getPerimeter());
            System.out.println("The area of the triangle4 is " + triangle4.getArea());
            System.out.println();
        } catch (IllegalTriangleException ex) {
            System.out.println("Exception: " + ex);
        }

        try {
            Triangle triangle5 = new Triangle(2, 4, 9);     // try to create an illegal triangle
            System.out.println(triangle5.toString());
            System.out.println("The perimeter of the triangle5 is " + triangle5.getPerimeter());
            System.out.println("The area of the triangle5 is " + triangle5.getArea());
            System.out.println();
        } catch (IllegalTriangleException ex) {
            System.out.println("Exception: " + ex);
        }

        System.out.println();
        System.out.println(Triangle.getNumberOfObjects() + " triangles constructed");
        System.out.println(Triangle.illegalAttempts() + " triangle(s) failed to construct");
    }

相关问题