Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

Java custom exception preventing from creating object of different parameter

I'm creating Points for multi-dimensional graph and store them in a List. First created Point is setting the dimension for every next Point created -> for example; First Point I created is 3 dimensional, so I want to throw an exception if any next created Point is not 3 dimensional.

This is my Point class.

public class Point {
    private final int DIMENSIONS;
    private final int[] position;

    public Point(int dimensions) {
        DIMENSIONS = dimensions;
        position = new int[DIMENSIONS];
    }

    public void setPosition(int dimention, int value) {
        position[dimention] = value;
    }

    public int getPosition(int dimention) {
        return position[dimention];
    }
}

Custom exception class.

public class WrongNumberOfDimensionsException extends Exception {

    private final int expectedDimensions;
    private final int actualDimensions;

    public int getExpectedDimensions() {
        return expectedDimensions;
    }

    public int getActualDimensions() {
        return actualDimensions;
    }

    public WrongNumberOfDimensionsException(int expectedDimensions, int actualDimensions) {
        this.expectedDimensions = expectedDimensions;
        this.actualDimensions = actualDimensions;
    }  
}

And GeometricShape class, where I'm storing my points.

public class GeometricShape implements GeometricShapeInterface {

    private static List<Point> pointList;

    public GeometricShape() {

        pointList = new ArrayList<>();
    }

    public void add(Point point) throws WrongNumberOfDimensionsException {

        if(pointList.size() < 1) {
            pointList.add(point);
        } else {
            throw new WrongNumberOfDimensionsException() // Don't know what to do here
        }

    }
}

Main function if needed.

public static void main(String args[]) {
    GeometricShape s = new GeometricShape();

    Point p1 = new Point(3);
    p1.setPosition(0, 1);
    p1.setPosition(1, 1);
    p1.setPosition(2, 1);
    Point p2 = new Point(2);
    p2.setPosition(0, 4);
    p2.setPosition(1, 15);

    s.add(p1);
    s.add(p2); // exception ?

}

Comments