i want to sort a list of two dimensional points based on their polar angles with respect to a particular point. this will a part of a bigger code to find collinear objects from a set of points.
the method i thought of for doing this is is:

  1. create an arraylist of Point2D points
  2. use the POLAR_ORDER comparator of the above Point2D class.

the code i thought of for this is :

// setting things up and stuff

ArrayList<Point2D> p = new ArrayList<Point2D>();

// more code that i'll have to think of

Collections.sort(p, p.get(0).POLAR_ORDER);

// other stuff

will the above two lines work? i really dont know what to put in between them yet, so im yet to run simple tests...
if the above two lines work then ill proceed in the way that iv thought of, else back to the drawing board..

edit: im intending to sort the points according to polar angle it makes with the 1st point contained in the arraylist. im assuming p.get(0) gives the 1st element... ??

Edited 3 Years Ago by somjit{}

Interesting question! To find all the colinear points presumably you can't just take their angles from one arbitrary point - you'll have to repeat that process using each point in turn as the "particular point"?

If this is really just about colinear, the maybe there's a simpler answer using the formula for the area of triangle - take the triangle defined by 3 points for its vertexes, and if and only if the area is zero then the points must be colinear. If you're using the Princeton algorithms Point2D class, as opposed to the standard JDK Point2D, (wich I assume you are becuase of the ref to POLAR_ORDER) then you can use its area2 method directly.

you'll have to repeat that process using each point in turn as the "particular point"

thats exactly what i want to do.. but i just wrote that code as an example to show what i want to do with each of the points.

If you're using the Princeton algorithms Point2D class, as opposed to the standard JDK Point2D, (wich I assume you are becuase of the ref to POLAR_ORDER)

that is what im using , but the problem is , im all messed up with comparators and comparables. that particular class has so many different types that im just scratching my head with them trying to understand which ones to use and where!

i understand the part about using area. the area2 variable you spoke of falls in the ccw() method , which is itself called from within POLAR_ORDER under a special case.... which i dont understand either ! :(

all i do understand about the collinearity using the area procedure and the ccw() method is that it calculates area based on cross operation .
cross operation on 3 points return the area of the parallelogram that can be obtained using three points, and since area of triangle that shares a base with a side of a parallelogram is half the parallelograms area , cross product of 3 points give twice the triangles area , and using this , ccw() returns

-1 for point being in clockwise order with respect to the particular point being tested
+1 for counter-clockwise order
0 for 3 points being collinear

i want to ask a question here about comparables and comparators , when calling a system sort using these methods , does java automatically know how to work with the comparisons? and we just specify that what will be returned when java uses the comparison methods with particular arguments from the collection/array ?

sorry if im being vague... comparators and comparables are really confusing me...

edit: there was a slide that had a short explanation of the point2D class , there , it was written that the comparators like POLAR_ORDER etc are "one comparator for each point" . i assume this means that using the POLAR_ORDER comparator , we can sort all other points wrt that one particular point right ? the point from which the comparator is called using the dot operator?

Edited 3 Years Ago by somjit{}

Comparators are simpler than you probably think. When the Collections class is sorting data it needs to know what order to put them in. Some data types (eg integers) have "natural ordering", but objects in general do not. A Comparator just takes two objects and tells you which comes first in the sort order.
All the sort algorithms reduce to comparing pairs of objects then moving them around based on which object goes first. The sort algorith selects a pair of objects the asks the Comparator which comes first. The it picks anothe pair etc etc.
The stuff about "one point" doesn't quite make sense. A Comparator<Point2D> just compares any two Point2D instances that get passed to it.

The sort algorith selects a pair of objects the asks the Comparator which comes first.

im getting it now.. and thanks to eclipse , i also got somewhat an idea about the syntax to use. let me try this now.. :)

i did some basic stuff , and ran a simple test. looks good so far. however , even with a simple set of around 10 points , the whole process is taking around 16 milliseconds to finish... and im getting a feeling that this is too slow...

this is the test code i made , is there some ways to make it faster?

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

public class Point{

    ArrayList<Point2D> p = new ArrayList<Point2D>();
    BufferedReader is = null;

    public Point() throws IOException{

        is = new BufferedReader(new FileReader("C:/Documents and Settings/Somjit/Desktop/points.txt"));
        String line;
        try{
            Point2D pt;
            while((line = is.readLine())!= null){
                String[] parsed = line.split(" ");
                assert parsed.length == 2 : "line has more than two coords : not allowed";
                pt = new Point2D(Double.parseDouble(parsed[0]), Double.parseDouble(parsed[1]));
                p.add(pt);
            }
        }catch(IOException e){
            System.out.println(e);
        }finally{
            is.close();
        }

        System.out.println(" sorting for lowest point");
        Collections.sort(p);
        System.out.println(" lowest point obtained: " + p.get(0));
        Collections.sort(p, p.get(0).POLAR_ORDER);
        System.out.println(" after sorting wrt lowest point");
        for(Point2D point : p){
            System.out.print(" " + point);
        }

    }
}

// and the tester
import java.io.IOException;

public class pointTester {

    public static void main(String[] args) throws IOException{
        final long startTime = System.currentTimeMillis();
        Point p = new Point();
        final long duration = System.currentTimeMillis() - startTime;
        System.out.println("\n\n\n running duration in milli seconds : " + duration);
    }

}

Two observations:
16 mSec is 1/60 sec Depending on your PC 1/60 sec may be the resolution of the timer, so maybe you can't mesaure less than that.
That time includes opening, reading, parsing, closing a file. That probably takes 99% of the time.

My guess is that you won't be able to measure the time for just the sort itself until you have an awful lot of data. Try timing a sort on thousands of random points (excluding creating the points).

ps I just "got" the polar order comparator and the "one point" stuff - it orders pairs of points by their angle measured from a specific reference point. That's why it's an inner instance class of Point2D; the enclosing instance is the reference point. Obvious, really.

Edited 3 Years Ago by JamesCherrill

Try timing a sort on thousands of random points

that would be great if coupled with some gui stuff.. like having a frame that would display on it the points created. i would have a visual understanding of the points created and if the code is doing what it should.

however , i have zero gui experience , and although there is a princeton draw() class that we are supposed to use for gui functions , im only just starting to get the hang of Point2D , and that draw() code has exactly 1126 lines .... so... its not for me right now ... :P

can you suggest some simpler things/links that will be good enough for just the needs above?

What you ask is not difficult, and learning about it will be very valuable anyway, so here goes:
You need a window with a simple JPanel in it. You override the JPanel's paintComponent method to draw your points. The first two steps of the Oracle tutorial will get you that far (ignore step 3), and you can just copy/paste their code...
http://docs.oracle.com/javase/tutorial/uiswing/painting/step1.html

In your paintComponent method, to draw the points you can just start with a little circle for each point in the ArrayList, eg

for (Point2D point : myListOfPoints) {
   g.fillOval(point.x, point.y, 3, 3); // 3 pixel diameter filled circle at x, y
   // assumes the points fit in the pixel sixe of the window, eg 0 < x,y < 200
}

i tried implementing the code from the link you gave , but as the Point2D class holds the point co ordinates as private , i couldnt do the for loop like you said above. i did a bit of an experiment , and learned a bit of basic GUI from the book Head First Java , and wrote a few lines of code. however , even though im getting the frame , the points arent showing up...

i created a new frame , from within which i call a new panel. in my panel class , i keep an inner class myPoints . each myPoints point has integer x and y as the co ordinates , there is a setter that takes in a String array from the loop where the original inputs from the file are read and parsed. finally i keep an arraylist of such points, on which i call the foreach loop you described above.

this is the resultant code:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Point {

    ArrayList<Point2D> p = new ArrayList<Point2D>();
    BufferedReader is = null;

    public Point() throws IOException{

        is = new BufferedReader(new FileReader("C:/Documents and Settings/Somjit/Desktop/points.txt"));
        String line;
        try{
            Point2D pt;
            myDrawPanel outer = new myDrawPanel();

            while((line = is.readLine())!= null){
                String[] parsed = line.split(" ");
                assert parsed.length == 2 : "line has more than two coords : not allowed";
                pt = new Point2D(Double.parseDouble(parsed[0]), Double.parseDouble(parsed[1]));
                p.add(pt);
                outer.setPoints(parsed);
            }
        }catch(IOException e){
            System.out.println(e);
        }finally{
            is.close();
        }

        System.out.println(" sorting for lowest point");
        Collections.sort(p);
        System.out.println(" lowest point obtained: " + p.get(0));
        Collections.sort(p, p.get(0).POLAR_ORDER);
        System.out.println(" after sorting wrt lowest point");
        for(Point2D point : p){
            System.out.print(" " + point);
        }
        displayGui();

    }

    public void displayGui(){
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        myDrawPanel canvas = new myDrawPanel();
        frame.getContentPane().add(BorderLayout.CENTER , canvas);
        frame.setSize(1000,1000);
        frame.setVisible(true);
    }


}
class myDrawPanel extends JPanel{

    class myPoints{
        int x;
        int y;
        public myPoints(int x, int y){
            this.x = x;
            this.y = y;
        }

    }
    ArrayList<myPoints> pointsList = new ArrayList<myPoints>();
    myPoints plotPoints;

    public void setPoints(String[] parsed){
        System.out.print(" " + "a"); // just a debug print
        plotPoints = new myPoints(Integer.parseInt(parsed[0]), Integer.parseInt(parsed[1]));
        pointsList.add(plotPoints);
    }


    public void paintComponent(Graphics g){     

        g.fillRect(0, 0, this.getWidth(), this.getHeight());
        Color pointColor = new Color(255,255,255);
        g.setColor(pointColor);
        for (myPoints point : pointsList) {
               g.fillOval(point.x, point.y, 3, 3);
            }
    }
}

compared to the 1st code i posted , this code has new things at lines 27,34 and from line 50 onwards.

Edited 3 Years Ago by somjit{}

as the Point2D class holds the point co ordinates as private , i couldnt do the for loop like you said

That's standard OO stuff - make the data private and provide o=public accessor methods. Just use the public accessor methods x() and y() in the outline code I suggested

One reason you see nothing is that you create two panels - one on line 58 which you add to the frame, and one on line 27 which you populate with data. Forget the one on line 27 etc, and just pass the real array of points to the panel's constructor, and use the accessor methods to access the x and y values.

Edited 3 Years Ago by JamesCherrill

Just use the public accessor methods x() and y()

i completely overlooked that part! i guess my eyes was serching for some method whose name began with a "get.." . being able to access point2d's co ords should make things simpler :)

i did as you said , and i am getting the points as i should , although i had to change one line a bit.

i modified the line inside the foreach loop you gave with this g.fillOval((int)point.x()*25, (int)point.y()*25, 4, 4); but that was only because i gave points in the range of (2,2) to (6,7). wouldnt have needed the scale change for more spaced apart points.

but now thats done? any ways i can print out the co ordinates beside each point on the plot? that would make the plot more make it more readable i guess...

You can print anything anywhere on your panel...
g.drawString("some text!",x,y);
... so you can use that to print the coords or just the position in the list at the appropriate x,y for each point.
YOu may wany to use setFont to seta smaller font size - see the API doc for Graphics.

iv been trying to figure a part out but so far have been unsuccessful.

success so far :
All the sorting and everything is done , got a better hang of comparators , am able understand the gui parts , and figured a few ways to use a pre built StdDraw code that we are supposed to use too. also , changed the Point class to fit the given API.

problem now is how to display the collinear points in a per line basis , without repetition. ie , no two permutations of the same line points should be printed.

im posting my tester method below :

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class pointTester {

    public static void main(String[] args) throws FileNotFoundException {
        String file = args[0];
        Scanner h = new Scanner(new File(file));
        int num = h.nextInt();

        ArrayList<Point> p = new ArrayList<Point>();

        // draw each point.
        StdDraw.setCanvasSize(800, 800);
        StdDraw.setXscale(0, 30000);
        StdDraw.setYscale(0, 30000);
        StdDraw.setPenRadius(.009);
        StdDraw.setPenColor(StdDraw.BLUE);
        for (int i = 0; i < num; i++) {
            p.add(new Point(h.nextInt(), h.nextInt()));
            p.get(i).draw();
        }

        //sort the points based on lowest y and print
        Collections.sort(p);
        for (Point pt : p) {
            System.out.println(pt);

        }

        //creates a copy of the arraylist
        ArrayList<Point> test = new ArrayList<Point>(p);

        // made this one to hold collinear points , but not too sure how to use it 
        ArrayList<Point> col;


        //and the confusion starts here onwards: 

        for(int i = 0; i < num ; i++){
            //sort the arraylist accoring to slope wrt lowest point obtained previously.
            Collections.sort(p, test.get(i).SLOPE_ORDER);
            Point thisPoint = p.get(0);
            double slope = thisPoint.slopeTo(p.get(1));
            col = new ArrayList<Point>();

            for(int j = 2 ; j < num ; j++ ){
                Point newPoint = p.get(j);
                double newSlope = thisPoint.slopeTo(newPoint);

                // 1. treat points with equal slopes as collinear
                // 2. put collinear points on col arrayList(lenght of each arraylist atleast 3),

            }


        }

        // sort all the different arraylists obtained for each line on one particualr basis
        // compare them , eliminationg duplicates
        // display unique collinear points , thus no permutations of same line will be displayed.


    }


}

im trying to figure out how to code the parts iv kept as comments inside the for() loops . i really dont know what to do here... if there is some other way to solve this than what im thinking , please do let me know. im kind of at a loss...

the input file im working with :

8
10000      0
    0  10000
 3000   7000
 7000   3000
20000  21000
 3000   4000
14000  15000
 6000   7000

the image obtained after drwaing the 8 pairs of points:

f72a8314506c830cc6ef3031f400737c

new Point class:

import java.util.Comparator;

public class Point implements Comparable<Point> {
    private int x; // Cartesian
    private int y; // coordinates

    // create and initialize a point with given (x, y)
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    // accessor methods
    public int x() {
        return x;
    }
    public int y() {
        return y;
    }

    public double slopeTo(Point that) {
        return ((double)(that.y - this.y) / (that.x - this.x)); // to avoid division by zero and other stuff associated with integer division
    }

    // draw point using standard draw
    public void draw() {
        StdDraw.point(x, y);
    }

    // draw the line from this point to that point
    public void drawTo(Point that) {
        StdDraw.line(this.x, this.y, that.x, that.y);
    }

    // return string representation of this point
    public String toString() {
        return "(" + x + ", " + y + ")";
    }

    @Override
    public int compareTo(Point that) {
        if (this.y < that.y)
            return -1;
        if (this.y > that.y)
            return +1;
        if (this.x < that.x)
            return -1;
        if (this.x > that.x)
            return +1;
        return 0;
    }

    public final Comparator<Point> SLOPE_ORDER = new slopeOrder();

    private class slopeOrder implements Comparator<Point> {

        public int compare(Point q1, Point q2) {
            double dx1 = q1.x - x;
            double dy1 = q1.y - y;
            double dx2 = q2.x - x;
            double dy2 = q2.y - y;

            if      (dy1 >= 0 && dy2 < 0) return -1;    // q1 above; q2 below; thus q1 less
            else if (dy2 >= 0 && dy1 < 0) return +1;    // q1 below; q2 above
            else if (dy1 == 0 && dy2 == 0) {            // 3-collinear and horizontal
                if      (dx1 >= 0 && dx2 < 0) return -1;
                else if (dx2 >= 0 && dx1 < 0) return +1;
                else                          return  0;
            }
            else return -ccw(Point.this, q1, q2);     // both above or below

            // Note: ccw() recomputes dx1, dy1, dx2, and dy2
        }
        private int ccw(Point a, Point b, Point c) {
            double area2 = (b.x-a.x)*(c.y-a.y) - (b.y-a.y)*(c.x-a.x);
            if      (area2 < 0) return -1;
            else if (area2 > 0) return +1;
            else                return  0;
        }
    }

}

Edited 3 Years Ago by somjit{}

Since nobody seems to know exactly where this is going, I would aim for clear, open, and extendable, rather than "just good enough". My instinct here is for

class Line { 
   private ArrayList<Point> points // 3 or more points defining this line
   public addPoint(Point p) etc
   public compareTo(Line l2) // equal if have same Points, even if order is different
   etc etc
}
...
ArrayList<Line> foundLines ....

thank you for keeping up with me .

Since nobody seems to know exactly where this is going

basically a code which takes in points from a input file , sorts them in a certain order by using comparables and comparators , and then analyses the collection of points and prints out in command line the points which are collinear, without repition. i originally made the thread as i was confused with comparators . I apologise if iv bloated the thread up.

regarding comparing the two lines ,
will i be correct in saying Arrays.equals(line1, line2) will compare the two arraylists of points , and will return as equal even if ordering of points are different? i was reading here where it was mentioned that .equals() is badly broken.. ill have to read more into this though..

Edited 3 Years Ago by somjit{}

I didn't mean to suggest that the project was out of control, just that it's partly exploratory in nature, and who knows where exploring may lead?

Yes, Arrays.equals isn't exactly broken (it complies with its own documentation), but it probably won't do what you want. I'd go with implementing Comparable, or at least equals, in your Line class.

i was writting a small testcode for checking these arraylist comparison stuff. my basic goal was to sort the same array in two different orders , and each sorted array in essence will be like a line , they will have same member points , but at different locations. then i would compare them using the compareTo method as you pointed out, and thus check if they are equal or not. but , im stuck again... i cant understand what to do... and this is a very sinking feeling...

my test code :

import java.util.ArrayList;
import java.util.Scanner;
import java.util.Collections;

public class equalityTester{

    ArrayList<Point> p = new ArrayList<Point>();
    Scanner is;

    public equalityTester(String filename){
        is = new Scanner(filename);
        setup();
    }

    private void setup(){
        int num = is.nextInt();
        Point pt;
        int loop = 0;
        while(loop < num){
            pt = new Point(is.nextInt(), is.nextInt());
            p.add(pt);
        }

        System.out.println(" entered points are : ");
        for(Point point : p){
            System.out.println(point);
        }

        Collections.sort(p); // sort acc to internal ordering
        ArrayList<Line> l = new ArrayList<line>();
        l.add(p);
        Collections.sort(p, p.get(0).SLOPE_ORDER); // sort acc. to slope
        l.add(p);

        // dont know what to do next , as i cant figure out the compareTo of line class


    }
}

class line implements Comparable<line>{
    ArrayList<Point> line;
    public line(ArrayList<Point> line){
        this.line = line;
    }
    @Override
    public int compareTo(line that) {
        // dont know what to do here        
    }
}

Edited 3 Years Ago by somjit{}

One idea would be to keep a Line's Points in sorted order then you could compare two Lines by comparing their points in a loop one at at a time - if all the Points are equal then the Lines are the equal.
A totally different approach would be to calculate the slope and intercept of each line from any two of its points, then two lines are equal if they have the same slope & intercept.
Which you use (or maybe something else again) depends on exactly what YOU intend to mean when you say "these two lines are equal" - ie is that because they are defined by the same set of points or because if you draw them one will be exactly on top of the other?

the slope and intercept method sounds great. should be easy to implement too i think. no need for looping through arraylists anymore :)

however if i do use that method , i really dont need the return +1 , -1 parts of a compareTo method anyways do i? as im just testing for equality... so in that case what to do? if i use a compareTo() i guess i have to keep stuff for -1 and +1 , the only thing i can think of regarding returning +1 -1 , is that it might be based on slopes being more or less than that of the invoking point.

if im only cencerned with the return 0 part , can i use something else instead of a compareTo() ?

Edited 3 Years Ago by somjit{}

You need equals as well (should be equivalent to compareTo returning 0) so you can use useful Collections such as TreeSet. If there's no obvious meaning for > and <, then just return +1 or -1 in any consistent kind of way. You can always change that later if you find a real need to order Lines.

this is the compareTo() code i came up with , havent yet run the whole code , coz i still have some other parts to look into ... but can you take a look at this and suggest if this is ok or not ? i would be a bit releived on atleast this part then...

class Line implements Comparable<Line>{
    ArrayList<Point> lineOfPoints;
    double slope = slope(this);
    double b = b(this);
    double x0 = -1*(b/slope);
    double y0 = b;

    public Line(ArrayList<Point> line){
        this.lineOfPoints = line;
    }

    // y = mx + b , where b is a constant
    public double b(Line anyLine){
        Point anyPoint = anyLine.lineOfPoints.get(0);
        int x1 = anyPoint.x();
        int y1 = anyPoint.y();
        double constant = y1 - slope*x1;
        return constant;
    }

    public double slope(Line anyLine){
        Point p1 = anyLine.lineOfPoints.get(0);
        Point p2 = anyLine.lineOfPoints.get((lineOfPoints.size() - 1));
        double slope = p1.slopeTo(p2);
        return slope;
    }
    @Override
    public int compareTo(Line that) {


        if(this.slope > that.slope ) return +1;
        if(this.x0 > that.x0 ) return +1;
        if(this.y0 > that.y0 ) return +1;
        if(this.slope < that.slope ) return -1;
        if(this.x0 < that.x0 ) return -1;
        if(this.y0 < that.y0 ) return -1;
        return 0;


    }
}

You need equals as well

i read in the java API that it takes in Object as argument . so do i need any casting or anything as such to convert that to the particular stuff im working with?
also , as you mentioned equals is just the return 0 part of the compareTo() , so can i do this :

    public boolean equals(Line that) {


        if(this.slope > that.slope ) return false;
        if(this.x0 > that.x0 ) return false;
        if(this.y0 > that.y0 ) return false;
        if(this.slope < that.slope ) return false;
        if(this.x0 < that.x0 ) return false;
        if(this.y0 < that.y0 ) return false;
        return true;


    }

the slope and b methods are ordinary instance methods of the Line class - so no need to pass in a Line parameter - just return the b or slope for the current object (this).

equals(Line that) is perfectly OK, for any other kind of parameter Java will use the inherited method from Object, which will return false.

Because you are using floating point numbers you may want to revisit those comparisons, you're aasuming an exact == will be possible, when maybe the best you will get equal-within-n-decimal-places kind of equality.

im down with

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at equalityTester.setup(equalityTester.java:16)
    at equalityTester.<init>(equalityTester.java:12)
    at equalityTester.main(equalityTester.java:48)

apparantly this seems to be a very popular error , but i didnt find any solution to it on the web.

my input file is this :

8
10000 0
0 10000
3000 7000
7000 3000
20000 21000
3000 4000
14000 15000
6000 7000

and my class is this :

import java.util.ArrayList;
import java.util.Scanner;
import java.util.Collections;

public class equalityTester{

    ArrayList<Point> p = new ArrayList<Point>();
    Scanner is;

    public equalityTester(String filename){
        is = new Scanner(filename);
        setup();
    }

    private void setup(){
        int num = is.nextInt();
        Point pt;
        int loop = 0;
        while(loop < num){
            pt = new Point(is.nextInt(), is.nextInt());
            p.add(pt);
        }

        System.out.println(" entered points are : ");
        for(Point point : p){
            System.out.println(point);
        }

        Collections.sort(p); // sort acc to internal ordering
        ArrayList<Line> L = new ArrayList<Line>();
        Line line1 = new Line(p);
        Collections.sort(p, p.get(0).SLOPE_ORDER);
        Line line2 = new Line(p);

        L.add(line1);
        L.add(line2);

        int comparison = line1.compareTo(line2);
        if(comparison == 0)
            System.out.println("equal");

        // dont know what to do next , as i cant figure out the compareTo of line class


    }
    public static void main(String[] args){
        String filename = args[0];
        equalityTester et = new equalityTester(filename);
        System.out.println("\n\n\n\n done executing ");
    }
}

iv modified the line class as you mentioned in the last post. i didnt post it to save space and clutter.

i woke up and i thought i should also mention this , last one month or so , iv used buffered reader for my parsing stuff , and it ran ok. i just used scanner here as im only allowed to import java.util and java.lang. . ill be trying to work this around now again... i wrote another tiny code , which takes the same file as input , uses the same nextInt() , and this one seems to run just fine, whereas the previous code i posted , despite having the same methods , throws exception...

this is the code i tested for scanner

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;


public class scanTester {

    public static void main(String[] args){
        String filename = args[0];
        try {
            Scanner is = new Scanner(new File(filename));
            while(is.hasNext()){
                System.out.println(" " + is.nextInt());
            }
        } catch (FileNotFoundException e) {
            System.out.println(e);
            e.printStackTrace();
        }

    }


}

Edited 3 Years Ago by somjit{}

Scanner is = new Scanner(new File(filename)); // works
is = new Scanner(filename); // does not work

API doc says :
public Scanner(String source)
Constructs a new Scanner that produces values scanned from the specified string.
Parameters: source - A string to scan

ps It's really time to stop using a thread about Comparators as a dumping place for every Java query you have. Please start a new Thread for each new topic.

This question has already been answered. Start a new discussion instead.