Question: Modify Listing 18.8, TowerOfHanoi.java, so that the program finds the number of moves needed to move n disks from tower A to tower B. Listing

Modify Listing 18.8, TowerOfHanoi.java, so that the program finds the number of moves needed to move n disks from tower A to tower B.

Listing

1 import java.util.Scanner; 2 3 public class Tower0fHanoi { /** Main method

*/ public static void main(String[] args) { // Create a Scanner Scanner

1 import java.util.Scanner; 2 3 public class Tower0fHanoi { /** Main method */ public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner (System.in); System.out.print("Enter number of disks: "); int n - input.nextInt(); 10 11 12 13 14 15 // Find the solution recursively System.out.println("The moves are:"); moveDisks(n, 'A', 'B', 'C'); 16 /** The method for finding the solution to move n disks 17 from fromTower to toTower with auxTower */ 18 public static void moveDisks(int n, char fromTower, 19 20 21 22 23 24 25 26 char toTower, char auxTower) { if (n == 1) // Stopping condition System.out.printin("Move disk " + n + " from " fromTower + " to " + toTower); else { moveDisks(n - 1, fromTower, auxTower, toTower); System.out.println("Move disk " + n + " from fromTower + " to " + toTower); moveDisks(n - 1, auxTower, toTower, fromTower); 28 29 30 } n6700 90 Enter number of disks: 4 -Enter The moves are: Move disk 1 from A to C Move disk 2 from A to B Move disk 1 from C to B Move disk 3 from A to C Move disk 1 from B to A Move disk 2 from B to C Move disk 1 from A to C Move disk 4 from A to B Move disk 1 from C to B Move disk 2 from C to A Move disk 1 from B to A Move disk 3 from C to B Move disk 1 from A to C Move disk 2 from A to B Move disk 1 from C to B

Step by Step Solution

3.42 Rating (177 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

Output Enter number of disks4 The moves are Move disk 1 from A to C Move disk 2 from A to B Move dis... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Java Programming Questions!