Krent
Krent

Reputation: 29

Java - How to store values of a text file into an array using Scanner?

import java.io.*;

import java.util.*;

import java.text.*;

public class textFile {

    public static void main(String args[]) throws IOException {

        Scanner sf = new Scanner(new File("C:\\temp_Name\\DataGym.in.txt"));
        int maxIndx = -1;
        String text[] = new String[1000];
        while (sf.hasNext()) {
            maxIndx++;
            text[maxIndx] = sf.nextLine();
        }

        sf.close();

        double average[] = new double[100];

        for (int j = 0; j <= maxIndx; j++) {
            Scanner sc = new Scanner(text[j]);
            int k = 0;
            while (k <= 10) { //attempt to store all the values of text file (DataGym.in.txt) into the array average[] using Scanner
                average[k] = sc.nextDouble();
                k++;
            }
        }
    }
}

My code doesn't work and keeps giving me this error at the place where I store sc.nextDouble() into the k element of the array:

java.util.NoSuchElementException:

null (in java.util.Scanner)

Upvotes: 1

Views: 668

Answers (1)

Imposter
Imposter

Reputation: 251

You should check out the Scanner API. It is suspicious that you have a call to Scanner.hasNext() with a following call to Scanner.nextLine(). There are complimentary calls to check and then get from a Scanner. For instance if you really want the next line then you should check if Scanner.hasNextLine() before calling Scanner.nextLine(). Similarly you call Scanner.nextDouble() without preceding it with a call to Scanner.hasNextDouble().

Also like some of the comments mention you should use a debugger or print statements to see if you are getting what you expect you should be getting. Steps like this are necessary to debugging.

For instance after sf.close you could use System.out.println(Arrays.toString(text)) and judge if the array contains what you expect.

Hope this helps your debugging.

Upvotes: 1

Related Questions