What you first need to do is some debugging. I suggest you either run your code under a debugger and carefully follow the state of your variables as your code runs, or else sprinkle a bunch of println statements throughout your code: