-2

I am writing code to take input from a file which has records in a given format and then splitting them to display pincodes which i need to compare later and write the records. To do the comparision i am first taking all the pincode fields in the records and storing them in a array.I am able to display pincodes but there is an exception. My method code is below.

String[] getPincodesArray(String filename) {



String[] st=new String[30];

int index=0;

try {

    FileReader fr=new FileReader(filename);

    BufferedReader br=new BufferedReader(fr);

    String line=br.readLine();

    while(line!=null) {

        String s[]=line.split(",");



        String s1[]=s[1].split(";");

        st[index]=s1[1];

        index++;

        line=br.readLine();




    }


}

catch(Exception e) {


    e.printStackTrace();
}

return st;

}

when i am executing this function is main(),I am getting an exception but am able to display all pincodes.The output is

java.lang.ArrayIndexOutOfBoundsException: 1
at info.pack.Methods.getPincodesArray(Methods.java:270)
at info.pack.studentidpincode.main(studentidpincode.java:18)

560054 560076 560098 560054 560097 560087 560054 null null null..

I am able to see all pincodes, then why is the exception coming?

Karan Talasila
  • 429
  • 3
  • 6
  • 10

1 Answers1

0

Your file probably ends with a blank line. If that's the case, here's what happened:

  1. line=readLine() reads the blank line; line isn't null because, blank or not, that last line wasn't the end of the file, so the while loop executes an iteration;
  2. String s[]=line.split(",") gives you either one element or none in s, depending on whether line contained any spaces or not;
  3. Either way, s won't have the element at index 1 (and maybe not even an element at index 0!), so String s1[]=s[1].split(";") gets the inevitable ArrayIndexOutOfBoundsException.

A minimum solution is to detect and ignore blank lines in the input file:

while(line!=null) {
    if (!line.trim().isEmpty()){
        // process the line only if we know it has some data
    }
    line=br.readLine();
}

A better solution would go further by checking the result of each split to be sure that there is an element available at index 1 before actually trying to use that element:

while(line!=null) {
    if (!line.trim().isEmpty()){
        String s[]=line.split(",");
        if (s.length() >= 2) {
            String s1[]=s[1].split(";");
            if (s1.length() >= 2) {
                st[index]=s1[1];
                index++;
            }
            else 
                System.out.println("Missing semicolon");
        }
        else
            System.out.println("Missing comma");
    }
    line=br.readLine();
}
Kevin Anderson
  • 4,568
  • 3
  • 13
  • 21