Search code examples
javaarraysfileconvex-hull

Convex Hull - Reading from input file


I am trying to read the x,y coordinates from a file that has 1000 entries.

This is what I have so far:

    int n=4;
    Point2D []p = new Point2D[n];
    p[0]  = new Point2D(4,5);
    p[1]  = new Point2D(5,3);
    p[2]  = new Point2D(1,4);
    p[3]  = new Point2D(6,1);

I can open the file like this:

Scanner numFile = new Scanner(new File("myValues.txt"));
        ArrayList<Double> p = new ArrayList<Double>();
        while (numFile.hasNextLine()) {
            String line = numFile.nextLine();
            Scanner sc = new Scanner(line);
            sc.useDelimiter(" ");
            while(sc.hasNextDouble()) {
                p.add(sc.nextDouble());
            }
            sc.close();
        }
        numFile.close();

But I do not know how to create arrays with two values each time. Please let me know if you need more information.


Solution

  • All you really need to do is create a Point2D object (using the coords in your .txt file) at each iteration of the loop, then add that object to your array list of Point2D objects:

    For example:

    ArrayList<Points2D> p = new ArrayList<>();
    
    Scanner numFile = new Scanner(new File("myValues.txt"));
    
    String pointOnLine = numFile.readLine();
    
    while (numFile != null) //if line exists
    {
    
         String[] pointToAdd = pointOnLine.split(" +"); //get x y coords from each line, using a white space delimiter
         //create point2D object, then add it to the list  
         Point2D pointFromFile = new Point2D(Integer.parseInt(pointToAdd[0]), Integer.parseInt(pointToAdd[1]));
         p.add(pointFromFile);
         numFile = numFile.readLine();  //assign numFile to the next line to be read
    
    }   
    

    The tricky part (and the part you're stuck at I'm assuming), is extracting the individual x and y-coordinates from the file.

    What I have done above was use the .split() method to turn every single line into a string array of each number on the entire line, separated by a white space. Since each line should only contain two numbers (x and y), the array size will be 2 (elements 0 and 1 respectively).

    From there, we simply get the first element in the string array (the x-coordinate), and the second element (the y-coordinate), and then parse those strings into integers.

    Now that we have isolated the x and y from each line, we use them to create the Point2D object, and then add that object to the array list.

    Hope this clarifies things