0

I'm trying to take the contents of a file into an array. The file contents are positive and negative integers.

This is what I did to find how big I should make the array. inFile is my scanner. I am able to print the contents of inFile, but they won't go into the array. I just get null values.

    int arrayLength = 0;
    while (inFile.hasNextInt()){
        inFile.nextInt();
        arrayLength++;
    }

This is what I tried to do to get the file contents into the array.

    int[] nums = new int[arrayLength]; //make array according to arrayLength
    inFile.reset();
    //fill array with values from file
    for (int n = 0; n > arrayLength; n++) {
        nums[n] = inFile.nextInt();
    }

Thanks for your help.

clenard
  • 188
  • 2
  • 16

1 Answers1

0

When you use nextInt() in the first loop you're "moving" a virtual cursor over your stream and you cannot go back again.

Let's say you have an input like:

17
-15
13

Then, when you call nextInt() for the first time, your cursor move from 17 to -15. So calling nextInt() at each loop will necessarily cause to have null values in the second loop.

You should try to use dynamic arrays or maybe a list (which don't have a fixed size)

  • I thought that's what the Scanner.reset() method fixed. Shouldn't the cursor go back to the beginning? – clenard Apr 18 '14 at 17:48
  • Look at the [javadoc for scanner](http://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#reset--), it only resets the delimeter, locale and radix. – azurefrog Apr 18 '14 at 17:53