-1

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');
    }
}
ericbn
  • 10,163
  • 3
  • 47
  • 55
Jamiex304
  • 242
  • 1
  • 7
  • 26
  • You can do a `static int counter = 0;` And whenever you do `System.out.println("Move disc from "+a+" to "+b);` in `Han(...)` you can add `counter++;` below that. – Compass Sep 22 '14 at 21:10
  • @Compass can u show me where u would put that on my code above, it took me a while to get this working would rather not break it again – Jamiex304 Sep 22 '14 at 21:21
  • possible duplicate of [Counter for Towers Of Hanoi](http://stackoverflow.com/questions/10287847/counter-for-towers-of-hanoi) – ericbn Sep 22 '14 at 21:38

2 Answers2

0

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.
}
}
Mehdi
  • 582
  • 4
  • 14
0

Rather than introduce a static variable (which, among other concerns, isn't thread-safe), you could also return the count:

public static int Han(int m, char a, char b, char c){
  int count = 0;
  if(m>0){
    count += Han(m-1,a,c,b);
    System.out.println("Move disc from "+a+" to "+b);
    count++;
    count += Han(m-1,b,a,c);
  }
  return count;
}
Sbodd
  • 11,279
  • 6
  • 41
  • 42