Try debugging the code by adding printlns to show the variables values as they change and the execution flow.