I am developing a simple Tower of Hanio java programme. I have it giving me all the steps for the amount of disks the user inputs.
But Now I am stuck I want to put a counter at the end to give the user a clear number of steps rather than have them count them all
Here is my code, if you can help me,
add a count that would be great.
Any help would be great
import java.util.Scanner;
public class Hanoi{
public static void Han(int m, char a, char b, char c){
if(m>0){
Han(m-1,a,c,b);
System.out.println("Move disc from "+a+" to "+b);
Han(m-1,b,a,c);
}
}
public static void main(String[]args){
Scanner h = new Scanner(System.in);
System.out.println("How many discs : ");
int n = h.nextInt();
Han(n, 'A', 'B', 'C');
}
}
The easy way is to use a static variable like this:
import java.util.Scanner;
public class Hanoi{
static int stepsCounter = 0; // new Code here.
public static void Han(int m, char a, char b, char c){
if(m>0){
stepsCounter++; // new Code here.
Han(m-1,a,c,b);
System.out.println("Move disc from "+a+" to "+b);
Han(m-1,b,a,c);
}
}
public static void main(String[]args){
Scanner h = new Scanner(System.in);
int n;
System.out.println("How many discs : ");
n = h.nextInt();
Han(n, 'A', 'B', 'C');
System.out.println("Steps : " + stepsCounter); // new Code here.
}
}