Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Note: (I) For all assignments, always use comments to explain your program. Desc

ID: 3871364 • Letter: N

Question

Note: (I) For all assignments, always use comments to explain your program. Description of program: Write a Java program that will print the steps needed to solve a Towers of Hanoi puzzle given the number of disks. The program should first prompt the user for the number of disks. Then it should display the steps, one per line. Each step should indicate which peg to move a disk from, and which peg to move the disk to. The steps should also be sequentially numbered. Upload the java file into A2 folder of icollege. Sample Output: How many disks? (0 to end) 3 1: 1 to3 2: 1 to 2 3: 3 to 2 4: 1 to 3 5: 2 to 1 6: 2 to 3 7: 1 to 3 How many disks? (0 to end) 0

Explanation / Answer

Please find my code.

import java.util.Scanner;

public class TowerOFHanoi {

   static int steps = 1;

   public static void main(String[] args) {

       Scanner sc = new Scanner(System.in);

       System.out.print("How many disk? (0 to end) ");

       int nDisks = sc.nextInt();

      

       sc.close();

      

       if(nDisks > 0)

           doTowers(nDisks, '1', '2', '3');

   }

   public static void doTowers(int topN, char from, char inter, char to) {

       if (topN == 1) {

           System.out.println(steps++ +": " + from + " to " + to);

       } else {

           doTowers(topN - 1, from, to, inter);

           System.out.println(steps++ +": " + from + " to " + to);

           doTowers(topN - 1, inter, from, to);

       }

   }

}

/*

Sample run:

How many disk? (0 to end) 4

1: 1 to 2

2: 1 to 3

3: 2 to 3

4: 1 to 2

5: 3 to 1

6: 3 to 2

7: 1 to 2

8: 1 to 3

9: 2 to 3

10: 2 to 1

11: 3 to 1

12: 2 to 3

13: 1 to 2

14: 1 to 3

15: 2 to 3

*/

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote