I am trying to display the count of moves within a program that solves the Tower of Hanoi puzzle, but it keeps displaying the count more than once as seen in my output below
Input the number of rings: 2
Towers of Hanoi with 2 rings
1
3
3
I want it to only display the number 3 once, instead of 1, 3, 3. Here is my code below (For my assignment,I have to declare a static int count).
import java.util.Scanner;
public class Towers
{
static int count;
public static void doTowers(
int n, // Number of rings to move
int startPeg, // Peg containing rings to move
int auxPeg, // Peg holding rings temporarily
int endPeg ) // Peg receiving rings being moved
{
boolean b = true;
while(b){
if (n == 1){ // Base case - Move one ring
count = count + 1;
b = true;
}
if (n == 0){
b = false;
}
else{
// Move n - 1 rings from starting peg to auxiliary peg
doTowers(n - 1, startPeg, endPeg, auxPeg);
count = count + 1;
b = true;
// Move n - 1 rings from auxiliary peg to ending peg
doTowers(n - 1, auxPeg, startPeg, endPeg);
}
}
}
public static void main(String[] args)
{
Scanner conIn = new Scanner(System.in);
// Number of rings on starting peg.
int n;
System.out.print("Input the number of rings: ");
if (conIn.hasNextInt())
n = conIn.nextInt();
else
{
System.out.println("Error: you must enter an integer.");
System.out.println("Terminating program.");
return;
}
if (n < 1)
{
System.out.println("Error: you must enter an integer >= 1.");
System.out.println("Terminating program.");
return;
}
System.out.println("Towers of Hanoi with " + n + " rings ");
doTowers(n, 1, 2, 3);
System.out.println("This takes " + count + " moves.");
} }