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

Write a program to test the method \"towers.\" Specifically, have your main meth

ID: 3659136 • Letter: W

Question

 Write a program to test the method "towers."  Specifically, have your main method:  (a) Ask the user for the:      * Number of rings      * Source Tower (as a character; for example, A)         The Java statement for single character input looks like:             source_tower = sc.nextLine().charAt(0);         where "source_tower" is a char variable.  Don't        forget to prompt the user.      * Destination Tower (as a character; for example, C)      * Spare Tower (By the way, this can be determined in the       program itself, given that we already have the source       and destination.  However, to make things easier, feel       free to get it from the user.)  (b) Call on "towers" to print a list of instructions for solving the     version of the towers problem input by the user.  


Explanation / Answer

TowersMain.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TowersMain {
    public static void main(String args[]) throws IOException {
        TowersMain towersMain = new TowersMain();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter number of rings");
        int noOfRings = Integer.parseInt(br.readLine());
        System.out.println("Enter the source tower");
        char sourceTower = br.readLine().charAt(0);
        System.out.println("Enter the destination tower");
        char destinationTower = br.readLine().charAt(0);
        char spareTower = 'S';
        towersMain.towers(sourceTower, spareTower, destinationTower, noOfRings);
    }
    public void towers(char a,char b,char c,int n) {
       
        if(n==0)
        System.out.println("WRONG INPUT !!!");
        if(n==1)
        System.out.println("Move from " + a + " to " +c);
        if(n>1)
        {
            towers(a,c,b,n-1);
            towers(a,b,c,1);
            towers(b,a,c,n-1);
        }
       
    }
}

Sample Output:('S' is spare tower)

Enter number of rings
4
Enter the source tower
A
Enter the destination tower
B
Move from A to S
Move from A to B
Move from S to B
Move from A to S
Move from B to A
Move from B to S
Move from A to S
Move from A to B
Move from S to B
Move from S to A
Move from B to A
Move from S to B
Move from A to S
Move from A to B
Move from S to B

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