Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
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?
3 Answers
- husoskiLv 76 years agoFavorite 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.
- ?Lv 76 years ago
I think this depends on the contents of the text file. Does it have more than 11 doubles?
- JohnLv 76 years ago
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;
}
}