whla
whla

Reputation: 811

Reading a file into an array of objects

So once again I am having some trouble with Java. I'm not sure whether creating an array of objects is just harder in Java or I'm not used to it, but as far as I can tell it is correct now (let me know if not). So after all of that fiddling I moved onto file I/O. So here is where my current problems are arising.

public static void main(String[] args) {

    Coordinate[] locCoor = new Coordinate[100];
    Circle[] locCircles = new Circle[100];
    int track = 0;
    double X ,Y;

    Scanner scan;
    File file = new File("resource\\coordinates2.txt");

    try {
        scan = new Scanner(file);

        while(scan.hasNextLine()){
            String line = scan.nextLine();
            Scanner lineScanner = new Scanner(line);
            while(lineScanner.hasNextDouble()) {
                locCoor[track] = new Coordinate();
                X = lineScanner.nextDouble();
                if(lineScanner.hasNextDouble()) {
                    Y = lineScanner.nextDouble();
                    locCoor[track] = new Coordinate(X,Y);
                    track++;
                }
            }

            System.out.println(track);
        }
    }catch(FileNotFoundException e1) {
        e1.printStackTrace();
    }
}

I get the following as errors:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextDouble(Scanner.java:2413)
    **at implementation.main(implementation.java:133)**
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

Process finished with exit code 1

So at the stared line is my code and the starred error correspond, but after a lot of searching I can't seem to find any solution. I would really appreciate it if someone could point me in the right direction.

OH and I forgot to ask whether I should declare the arrays of objects (locCoor & locCircles) in the top or in the loop. I know I have both in my code.

Upvotes: 0

Views: 130

Answers (1)

Jigar Joshi
Jigar Joshi

Reputation: 240956

You are making sure it has one next element and reading next two

while(lineScanner.hasNext()) {
    X = scan.nextDouble();
    Y = scan.nextDouble();

consider cursor is at the second last element, it returns true because you have next element and you read last element that is fine, but again reading element in next statement would throw this error

Upvotes: 1

Related Questions