Towers Of Hanoi Java

北城以北 提交于 2019-12-02 10:40:10

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');
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!