Have you tried debugging the code by adding some println statements to print out the values of variables as the code executes so you can see where the code is going wrong?