Out of Bounds Exception? (Java)?

Scanner tempTXT = new Scanner(new File("KeyWestTemp.txt"));
Scanner humidTXT = new Scanner(new File("KeyWestHumid.txt"));

double[] temp = new double[11];
double[] humid = new double[11];
double[] heatIndex = new double[11];

for (int i = 0; tempTXT.hasNextDouble(); ++i)
{
temp[i] = tempTXT.nextDouble();
}

Why is this for loop running into an out of bounds exception?

husoski2015-09-26T19:05:18Z

Favorite Answer

If you have more than 11 numbers, that will happen.

You can stop early with a small change to the for loop:

for (int i = 0; tempTXT.hasNextDouble() && i<temp.length; ++i) {
...

That will stop when the array fills up. You can detect when that happens after the loop ends, if you like. If tempTXT.hasNextDouble() is still true, then there is unread data still in the Scanner.

david2015-09-26T18:37:43Z

I think this depends on the contents of the text file. Does it have more than 11 doubles?

John2015-09-27T01:28:06Z

try this...
import java.util.*;
import java.io.*;

public class Program {
public static void main(String[] args) {
final int SIZE = 11;
final String filePath = "d:/temp/temp.txt";
try {
double[] temp = load(filePath, SIZE);
System.out.println( Arrays.toString(temp));
} catch (FileNotFoundException ex) {
System.err.println(ex.getMessage());
}
}

private static double[] load(String filePath, int size) throws FileNotFoundException {
double[] results = new double[size];
Scanner file = new Scanner(new FileReader(filePath));
for (int i = 0; i < size && file.hasNextDouble(); i++) {
results[i] = file.nextDouble();
}
file.close();
return results;
}
}