Programming Projects 151 12 Specify design and implement a c
Programming Projects 151 12 Specify, design, and implement a class that c, keeps track of rings stacked on a peg, rather like phonograph records on a spindle. An example with five rings is shown here: Rings stacked on a peg The peg may hold up to 64 rings, with each ring having its own diameter. Also, there is a rule that re- quires each ring to be smaller than any ring under- neath it, as shown in our example. The class\'s member functions should include: (a) a constructor that places n rings on the pe where n may be as large as 64); use 64 for a default argument. These n rings have diameters from n inches (on the bottom) to 1-inch (on the top). (b) a constant member func tion that returns the number of rings on the peg. (c) a constant member function that returns the diameter of the top most ring. (d) a member function that adds a new ring to the top with the diameter of the ring as a parameter to the function). (e) a member func- tion that removes the topmost ring. (f an overload- ed output function that prints some clever representation of the peg and its rings. Make sure that all functions have appropriate preconditions to guarantee that the rule about ring sizes is enforced Also spend time designing appropriate private data. fields.
Solution
public class TowersOfHanoi {
public void solve(int n, String start, String auxiliary, String end) {
if (n == 1) {
System.out.println(start + \" -> \" + end);
} else {
solve(n - 1, start, end, auxiliary);
System.out.println(start + \" -> \" + end);
solve(n - 1, auxiliary, start, end);
}
}
public static void main(String[] args) {
TowersOfHanoi towersOfHanoi = new TowersOfHanoi();
System.out.print(\"Enter number of discs: \");
Scanner scanner = new Scanner(System.in);
int discs = scanner.nextInt();
towersOfHanoi.solve(discs, \"A\", \"B\", \"C\");
}
}
