0

I am trying to read a text file into a binary tree by using delimiters to separate the different fields. When I try to read it into the binary tree I get the array out of bounds erropackage Hospital;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;`

public class main {

    public static void main(String args[]) throws IOException 
    {
        BufferedReader in = new BufferedReader(new FileReader("patient.txt"));
        String line;

        BinaryTree hospital = new BinaryTree();

        while ((line = in.readLine()) != null) {
            String[]text = line.split(",");
            hospital.insert(text[0], text[1], text[2], text[3], text[4]);
        }
        in.close();

    }
}

enter image description here

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Teemo
  • 35
  • 7

1 Answers1

3

Change your split code with code below. If you don't use limit parameter, by default, split method eliminates the trailing empty elements. With -1 parameter this problem will be solved.

String[] text = line.split(",", -1);
rdonuk
  • 3,921
  • 21
  • 39
  • Thanks a lot it works now! – Teemo Mar 18 '16 at 19:12
  • @Teemo It looks like that you do not have text after the fourth comma in your text file at some of the places. This problem can be solved by this. – user2004685 Mar 18 '16 at 19:18
  • 1
    "by default, split method eliminates empty elements." is not correct. `split` doesn't remove any empty elements, but only trailing ones. Empty elements in the middle or at start are not removed. – Pshemo Mar 18 '16 at 19:20
  • Yes you are right, my memory mislead me. Thanks for the correction. – rdonuk Mar 18 '16 at 19:25