河内Java塔

时间:2012-04-23 23:19:28

标签: java towers-of-hanoi

这是我正在做的功课。我创建了两个班来玩河内塔。第一个是运行实际游戏类的跑步者。

import java.util.Scanner;

class TowersRunner {

    public static void main(String[] args) {
        TowersOfHanoi towers = new TowersOfHanoi();
        towers.TowersOfHanoi()
    }
}

public class TowersOfHanoi {
    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();

        solve(num_of_discs, 'A', 'B', 'C');
    }

    public static void solve(int first_disc, char aTower, char bTower, char cTower) {
        if (first_disc == 1) {
            System.out.println("Disk 1 on tower " + aTower + " moving to tower " + cTower);
        } else {
            solve(first_disc - 1, aTower, cTower, bTower);
            System.out.println("Disk " + first_disc + " on tower " + aTower + " moving to tower " + cTower);
            solve(first_disc - 1, bTower, aTower, cTower);
        }
    }
}

我需要帮助的是让TowersOfHanoi课程从我的TowersRunner课程开始。我还需要实现一个计数器显示游戏运行所需的次数,直到游戏在我的TowersOfHanoi课程中完成。基本上我需要System.out.println("It took" + counter + "turns to finish.");

这一行

我不知道如何正确实现计数器。此外,无法使runner类运行TowersOfHanoiTowersOfHanoi课本身运行良好,但作业的要求是我们至少需要2节课。

非常感谢帮助!!!请我一般是Java和编程的新手,请不要对我太过先进。 :d

2 个答案:

答案 0 :(得分:1)

您不需要TowersOfHanoi类中的main-Function。 而是用

替换您的TowersRunner main(String args [])方法
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');
}

答案 1 :(得分:0)

您可以在函数中传递计数器并使其递增。例如:

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

solve的第一次调用中,您将传入1.如您所见,每次递归调用solve时,计数器都会递增。

我会让你适应这个以返回计数器的最终值:)如果你只需要最终值,你根本不需要添加参数。只需让函数返回int而不是void,然后尝试弄清楚如何让它返回你想要的值。