问题
I have written a code for Towers Of Hanoi game. I don't know how to implement a counter for this program on how many times it ran. Any help will be much appreciated.
public class MainClass {
public static void main(String[] args) {
int nDisks = 3;
doTowers(nDisks, 'A', 'B', 'C');
}
public static void doTowers(int topN, char from, char inter, char to) {
if (topN == 1){
System.out.println("Disk 1 from " + from + " to " + to);
}else {
doTowers(topN - 1, from, to, inter);
System.out.println("Disk " + topN + " from " + from + " to " + to);
doTowers(topN - 1, inter, from, to);
}
}
}
回答1:
Change the return type of doTowers
from void
to int
, and set the return value to:
- if
topN == 1
, return 1; - else return the sum of two
doTowers()
plus 1.
The logic is similar to the algorithm of the problem. Have fun figuring it out!
You could also use a static global variable, but that's arguably bad programming style.
来源:https://stackoverflow.com/questions/10287847/counter-for-towers-of-hanoi