0

这是我正在做的作业。我创建了 2 个类来玩河内塔。第一个基本上是运行实际游戏类的跑步者。

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 类运行TowersOfHanoi. 课程本身运行良好,TowersOfHanoi但家庭作业的要求是我们至少需要 2 节课。

帮助将不胜感激!!!请我是Java和一般编程的新手,请不要对我太先进。:D

4

2 回答 2

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');
}
于 2012-04-23T23:48:52.033 回答
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递归调用时,计数器都会递增。

我会让你调整它以返回 counter 的最终值 :) 如果你只需要最终值,则根本不需要添加参数。只需让函数返回int,而不是void尝试弄清楚如何让它返回你想要的值。

于 2012-04-23T23:29:08.807 回答