user3135093
user3135093

Reputation: 31

Java servlet, reading from file, array out of Bound

I'm making a java servlet, and my task is to get the sum cost of products written in file:

category1 1 10 101 1 good1
category6 2 11 105 2 good5
category1 5 13 103 3 good4
category3 6 14 102 4 good2
category5 3 12 107 2 good1

The cost is in column 4. I have written:

    public int Sum_of_Elements()throws IOException{
    int sum = 0;
    BufferedReader br = new BufferedReader(new FileReader("/Data.txt"));
    String line = "";
    while((line=br.readLine())!=null){
        String[] columns = line.split(" ");
        sum = sum + Integer.parseInt(columns[4]);
    }
    System.out.println(sum);
    return sum;
}

And it doesn't work. When i go to servlet page I get

java.lang.ArrayIndexOutOfBoundsException: 4

What's wrong ? and how to fix it ?

Upvotes: 0

Views: 235

Answers (3)

Keerthivasan
Keerthivasan

Reputation: 12890

There is no index 4 in your columns array. Check your length of columns array. It will be lesser than 5, ArrayIndexOutOfBoundException is thrown when an illegal index of the array is accessed. Check the array length like this

  if( columns != null && columns.length >= 5 )
        sum = sum + Integer.parseInt(columns[4]);

Upvotes: 0

Soosh
Soosh

Reputation: 812

I ran your code as following and it was fine. make sure that your Data file is ASCII

import java.io.*;

public class Test{

public static void main(String[] args){
    try{
        int sum = 0;
        BufferedReader br = new BufferedReader(new FileReader("Data.txt"));
        String line = "";
        while((line=br.readLine())!=null){
            String[] columns = line.split(" ");
            sum = sum + Integer.parseInt(columns[4]);
        }
        System.out.println("Sun:" + sum);


        }catch(Exception e){
            System.out.println("error:" + e.getMessage());
        }
    }
}

Upvotes: 0

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40308

This code will fail if there is e.g. an empty line in the file, or a line formatted differently, or if the spaces are actually tabs (maybe there are more reasons). If you want to program defensively, you should do:

while((line=br.readLine())!=null) {
    String[] columns = line.split(" ");
    if( columns != null && columns.length >= 5 ) {
        sum = sum + Integer.parseInt(columns[4]);
    }
    else {
        // do what you must here; it may be an error to encounter such a line:
        throw new IllegalArgumentException("malformatted line: " + line);
        // or it may be OK to swallow the exceptional case
        // or you may only need to silently log it:
        logger.warn("malformatted line: " + line);
        // etc...
    }
}

Upvotes: 3

Related Questions