Reputation: 23
I am reading a file one line at a time. Each line in the file contains two numbers separated by a space. To work with both the numbers I used the split function and created an array to store the values. However, when I run my program it gives the arrayIndexOutofBoundsException. I have used the split function before. I can't seem to figure out why its displaying it now. Each line in my text file looks like this:
5 15
3 7
code:
for (int i=0; i<5; i++) {
try {
BufferedReader reader = new BufferedReader(new FileReader("measurements.rtf"));
String line = null;
line= reader.readLine();
String[] dimensions = line.split("\\s"); \\ splitting the line into an array
String widthS = dimensions[0];
String heightS = dimensions[1];
System.out.println(widthS);
width = Integer.valueOf(widthS);
height = Integer.valueOf(heightS);
System.out.println(height + width);
}
catch (FileNotFoundException e){
System.out.println("Error! D:\nFile not found.");
System.out.println(e);
}
catch(Exception e){
System.out.println("Error"); // array out of bounds exception
System.out.println(e);
}
My text file: 10 5
1000 1001
21 13
9999 888
345 1277
Upvotes: 1
Views: 905
Reputation: 2225
First, fix your code so you can really loop over all the file lines. Second check the length of the array. Third, print the line currently being read so you can se if the problem is with the file content.
Ex:
String fileName = "measurements.rtf";
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(fileName));
String line = null;
while((line = reader.readLine()) != null) {
System.out.println("Line: " + line);
String dimensions[] = line.split("\\s");
if(dimensions.length == 2) {
int width = Integer.parseInt(dimensions[0]);
int height = Integer.parseInt(dimensions[1]);
//...
} else {
//wrong content in line!
}
}
} catch (FileNotFoundException e) {
// Handle FileNotFoundException
} catch(IOException e) {
// Handle IOException
} catch(ArrayIndexOutOfBoundsException e) {
//Handle ArrayIndexOutOfBoundsException
}
Upvotes: 1
Reputation: 2461
your input file has empty line at the end of the file hence when "splitted"
String[] dimensions of size 1 and you get arrayIndexOutofBoundsException in the line
String heightS = dimensions[1];
Upvotes: 0