1
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)

3
  • Have you tried using System.out.println statements to check that text[j] actually contains what you think it does? Also, maybe you want k < 10 instead of k <= 10. Commented Mar 15, 2016 at 23:05
  • 1
    Better yet, step through your code one line at a time in your IDE debugger to see what's actually happening. In this case the exception means the input didn't contain what you were expecting. Commented Mar 15, 2016 at 23:06
  • You're only putting data into the first 10 elements of the average array, because you reset the index to 0 for every line Commented Mar 15, 2016 at 23:10

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.