Array Out of Bounds reading Archive

0

I'm having a problem with my code, in my text file that I read the last line is blank, and so it should not be read, however I'm getting out of bounds .

Sample file line:

  

Fernando & 60.9 & 166

Class main:

public static void main(String[] args) {
        ArrayList< Paciente > listaPacientes = new ArrayList< Paciente >(); 
        Paciente p = new Paciente();

        String filename = "F:\NetBeansProjects\IMC.txt";
        try {
            FileReader fr = new FileReader(filename);
            BufferedReader in = new BufferedReader(fr);
            String line = in.readLine();
            line = in.readLine();
            line = in.readLine();
            int a =4;
            while (line != null) {
                if(!line.startsWith(" ")){
                String result[] = line.split("&");
                listaPacientes.add(new Paciente(result[0], Double.parseDouble(result[1]), Integer.parseInt(result[2])));
                }
                line = in.readLine();
            }
            in.close();
        } catch (FileNotFoundException e) {
            System.out.println("Arquivo \"" + filename + "\" não existe.");
        } catch (IOException e) {
            System.out.println("Erro na leitura do arquivo " + filename + ".");
        }
    
asked by anonymous 27.09.2014 / 02:41

1 answer

2

If the goal is not to read the last blank line, the following statement might give you this exception:

listaPacientes.add(new Paciente(result[0], Double.parseDouble(result[1]), Integer.parseInt(result[2])));

Because the loop reading condition, line != null , checks only if there are no more rows, and if the "blank line" you refer to is an empty text "" , then this error will even occur. / p>

I suggest the following in the loop:

while (line != null) {
   if(!line.trim().isEmpty()){
        ...
   }
   line = in.readLine();
}

The exception is java.lang.ArrayIndexOutOfBoundsException usually occurs when you access an invalid position. Check the positions you get when you add new patients.

    
27.09.2014 / 14:04