TAGS :Viewed: 14 - Published at: a few seconds ago

[ Assigning text file to array ]

What I'm trying to do is get the values from a text value and then put them into an array of doubles. This is what I have but it doesn't accomplish my goal and prints out something that I don't want instead. I can't use array lists in this, just arrays.

This is what is in the text file: 70.3 70.8 73.8 77.0 80.7 83.4 84.5 84.4 83.4 80.2 76.3 72.0

Code:

    Scanner temperatureFile = new Scanner(new File("KeyWestTemp.txt"));
    double [] temperature = new double[12];

    while(temperatureFile.hasNext())
    {
        temperature[index] = temperatureFile.nextDouble();
        index++;
    }

Answer 1


I think that's the problem, but I might be wrong :-)

temperature[11] = temperatureFile.nextDouble(); // index?

To elaborate, you should have something like:

i = 0; // index 'runner'
while(temperatureFile.hasNext())
{
    temperature[i] = temperatureFile.nextDouble();
    i++;
}

However, this is not generic and you should really make an estimation of the size before declaring the array size.

Answer 2


Reut has the right idea. You are only ever assigning to the last element of the temperature array. Try:

for (int i = 0; temperatureFile.hasNext() && (i < 12); i++) {
    temperature[i] = temperatureFile.nextDouble();
}