user3965604
user3965604

Reputation:

Array out of bounds with string split

I'm reading from a text file, and setting parameters for my object (Dogs) to the information on the text file. It's a very simple task but I keep getting an array out of bounds error every time I try to access field[1] or field[2]. My code is as follows:

BufferedReader inFile = new BufferedReader(new FileReader("dogslist.txt"));
    String line  = inFile.readLine();
    int count = 0;
    Dogs[] parlour = new Dogs[16];

    while(line != null)
    {
    String[] field = line.split("#");
    int age = Integer.parseInt(field[2]);
    parlour[count] = new Dogs(field[0],field[1],age);
    System.out.println(parlour[count]);
    count++;
    line = inFile.readLine();
    }

Here are the contents of the text file:

Jerry#German Sheapord#4
Owen#cat#3
Morgan#MathsGenius#7

Text file of Error, textfile and code: http://pastebin.com/SznqE45i

Upvotes: 0

Views: 1109

Answers (1)

pczeus
pczeus

Reputation: 7868

You can solve your problem by being more 'defensive' in your code and validating each input line has content and that your array after splitting is as expected:

    BufferedReader inFile = new BufferedReader(new FileReader("dogslist.txt"));
    String line;
    int count = 0;
    Dogs[] parlour = new Dogs[16];

    while((line = inFile.readLine()) != null)
    {
        if(line.trim().length() > 0){
            String[] field = line.split("#");

            if(field.length < 3){
                System.out.println("Invalid line encountered: " + line);
            }
            else{
                int age = Integer.parseInt(field[2]);
                parlour[count] = new Dogs(field[0],field[1],age);
                System.out.println(parlour[count]);
                count++;
            }
        }
    }

Upvotes: 4

Related Questions