Try debugging the code by adding lots of println statements to show when different parts of the code is being executed and what the values of the variables are when it is executing.