This is a homework that I was working on. I have created 2 classes to play Towers of Hanoi. The first one is the basically a runner to run the actual game class.
You can just pass the counter in the function and have it be incremented. For example:
public static void solve(int first_disc, char aTower, char bTower, char cTower, int counter) {
System.out.println("Currently on turn #" + counter);
if (first_disc == 1) {
System.out.println("Disk 1 on tower " + aTower + " moving to tower " + cTower);
} else {
solve(first_disc - 1, aTower, cTower, bTower, counter + 1);
System.out.println("Disk " + first_disc + " on tower " + aTower + " moving to tower " + cTower);
solve(first_disc - 1, bTower, aTower, cTower, counter + 1);
}
}
In the first call of solve
, you would pass in 1. As you can see, each time solve
is called recursively, the counter is incremented.
I'll leave you to adapt this to return the final value of counter :) If you just need the final value, you don't need to add a parameter at all. Just make the function return int
instead of void
then try and figure out how you would make it return the value you want.
You don't need the main-Function in the TowersOfHanoi class. Instead, replace your TowersRunner main(String args[]) method with
public static void main(String[] args) {
System.out.println("Please enter the starting " + "number of discs to move:");
Scanner scanner = new Scanner(System.in);
int num_of_discs = scanner.nextInt();
TowersOfHanoi.solve(num_of_discs, 'A', 'B', 'C');
}