Array Out of Bounds reading File

Asked

Viewed 86 times

0

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

Line for example file:

Fernando&60.9&166

Main class:

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 + ".");
        }
  • 2

    Check the contents of result in the Debugger, especially the size() (maybe putting a Watchpoint when it is less than 3). It may be that the data is not in the format you want. What actually shows a weakness of the algorithm. It is always possible to come something unexpected.

  • 2

    Without fixing the weaknesses @bigown pointed out, you could still check if the line isEmpty().

1 answer

2

If the goal is not to read the last blank line, the following statement can generate this exception:

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

Because the reading condition of the cycle, line != null, checks only if there are no more lines and if the "blank line" you refer to is an empty string "", then this error will even occur.

I suggest the next in the cycle:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.