Question

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.

Was it helpful?

Solution

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top