Your problem is that you are NOT testing the length of the array until it is too late.
But I just want to point out that the way to solve this problem is to READ THE STACK TRACE.
The exception message will clearly tell you are trying to create an array with length -1, and the trace will tell you exactly which line of your code is doing this. The rest is simple logic ... working back to why the length you are using is -1.