I need to create a n-dimensional point with coordinates. The Constructor should take any number of coordinates. [closed]

StackOverflow https://stackoverflow.com/questions/20153747

Question

There is alot more in this project but I dont know how to start Im stuck on how to create a constructor with an array that will take a unknown number of dimensions in a point.

Was it helpful?

Solution

You can have an array as an argument for your constructor

public class MultiDemPoint{
    public MultiDemPoint(double[] coords){

    }
}

You will need to pass an array of doubles:

new MultiDemPoint(new double[]{4, 5.0, 3, 2, 6, 4.6});


You can also expect undefined number of coordinates as separated values

public class MultiDemPoint{
    public MultiDemPoint(double... coords){

    }
}

You can pass parametrs like new MultiDemPoint(4, 5.0, 3, 2, 6, 4.6); in this case.


Practice:

  • Create a new empty project in your IDE
  • Create MultDemPoint.java file with following code:

    public class MultiDemPoint{
        private double[] coords;
        //double... coords will automatically convert all supplied coordinates to the array,
        // we can store it in double[] coords.
        public MultiDemPoint(double... coords){
            this.coords = coords;
        }
    
        public void printCoords(){
            for(int i=0; i<coords.length; i++){
                System.out.println("Coordinate #"+i+": "+coords[i]);
            }
            System.out.println("");
        }
    }
    
  • Use this code for your Main.java

    public class Main {
            public static void main(String[] args){
            MultiDemPoint point1 = new MultiDemPoint(1,2,3,4);
            MultiDemPoint point2 = new MultiDemPoint(3);
            MultiDemPoint point3 = new MultiDemPoint(5.44444444,232323.12323,321321);
            System.out.println("Point1 coordinates:");
            point1.printCoords();
    
            System.out.println("Point2 coordinates:");
            point2.printCoords();
    
            System.out.println("Point3 coordinates:");
            point3.printCoords();
    
        }
    }
    

OTHER TIPS

If you don't want to pass an array, you can use so called "varargs".

public class Point
{
 public Point(double... x)
 {
 }
}

Then you can call:

new Point(1, 2, 3);
new Point(1, 2, 3, 4);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top