Have you tried debugging your code to see what it is doing?
If you do not have an interactive debugger, then add println statements to the code to print out the values of variables as they change and to show the execution flow. The printed output should help you understand what the program is doing.

That message is from your code. Why does your code throw that exception? What are the values of all the variables that cause that exception to be thrown? Add some more printlns to see the variables' values.