Question

In: Computer Science

My recursive Tower of Hanoi program does not render the correct index numbers. Also, it does...

My recursive Tower of Hanoi program does not render the correct index numbers. Also, it does not prompt user to enter the starting rod letter and the ending rod letter. Could you help me fix it?

Main.java

import java.io.*;

import java.util.List;

import java.util.Scanner;

public class Main {

int index = 1;

public static void main(String[] args) {

/**There is a stack of N disks on the first of three poles (call them A, B and C) and your job is to move the disks from pole A to pole B without

ever putting a larger disk on top of a smaller disk.*/

System.out.println();

System.out.println("Tower of Hanoi");

System.out.println("Program by Quang Pham");

System.out.println();

char startingrod = ' ';

char endingrod = ' ';

Scanner sc = new Scanner(System.in);

System.out.println("Enter the starting rod letter (A, B, or C).");

startingrod = sc.next().charAt(0);

System.out.println("Enter the ending rod letter (A, B, C).");

endingrod = sc.next().charAt(0);

if (startingrod == endingrod)

{

System.out.println("Sorry. Starting rod and ending rod cannot be the same.");

System.out.println("Enter ending rod letter (A, B, C)");

endingrod = sc.next().charAt(0);

}

if (startingrod == 'A' && endingrod =='C')

{

System.out.println("OK. Starting with discs 1, 2, 3, on rod A \n");

System.out.println("Moves are:");

int count = playHanoi (3,"A","B","C");

System.out.println();

System.out.println("All done.");

System.out.println("Took a total of " + count + " moves.");

System.out.println();

}

}

private static int playHanoi( int n, String from , String other, String to)

{ int count = 1;

//int index = 1;

if (n == 0)

return 0;

else if(n == 1)

{

System.out.printf("%d." + " Move disk "+ n +" from rod %s to rod %s \n", count, from, to);

//index++;

return count;

}

else{

count+= playHanoi(n-1, from, to, other);

System.out.printf("%d." + " Move disk " + n + " from rod %s to rod %s \n ", count, from, to);

count+=playHanoi(n-1, other, from, to);

}

//

return count;

}

}

The directions are:

  • Use three rods labeled A, B, and C
  • Use three discs labels 1 (smallest), 2 (medium size), and 3 (largest disc)
  • The program prompts you to enter the starting rod (A, B, or C)
  • The program prompts you to enter the ending rod (A, B, or C, but cannot be same rod as entered as starting rod)
  • The starting rod has discs 1, 2, 3, where 1 is on top of 2 is on top of 3 (just like we covered in class)
  • Your program should print out each move, showing clearly which disc goes from/to. See trace below.

Tower of Hanoi Program by YOUR NAME Enter Starting Rod (A, B, or C): A Enter Ending Rod (A, B, or C): A Sorry. starting and ending rod cannot be the same. Enter Ending Rod ((A, B, or C): C OK Starting with discs 1, 2, and 3 on rod A Moves are as follows: 1. Move disc 1 from rod A to rod C 2. Move disc 2 from rod A to rod B 3. Move disc 1 from rod C to rod B 4. Move disc. 3 from rod A to rod C 5. Move disk 1 from rod B to rod A 6. Move disk 2 from rod B to rod C 7. Move disk 1 from rod A to rod C All done. Took a total of 7 moves.

Any help with this program is greatly appreciated. Yours truly, Quang Pham

Solutions

Expert Solution

Here is the correction in your code.

import java.io.*;
import java.util.List;
import java.util.Scanner;

public class Main {
    // int index = 1;
    static int count = 1;
    public static void main(String[] args){
        /**There is a stack of N disks on the first of three poles (call them A, B and C) and your job is to move the disks from pole A to pole B without ever putting a larger disk on top of a smaller disk.*/ 
        System.out.println("\nTower of Hanoi");
        System.out.println("Program by Quang Pham\n");
        char startingrod = ' ';
        char endingrod = ' ';
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the starting rod letter (A, B, or C)."); 
        startingrod = sc.next().charAt(0);
        System.out.println("Enter the ending rod letter (A, B, C).");
        endingrod = sc.next().charAt(0);
        if (startingrod == endingrod)
        {
        System.out.println("Sorry. Starting rod and ending rod cannot be the same.");
        System.out.println("Enter ending rod letter (A, B, C)"); 
        endingrod = sc.next().charAt(0);
        }
        else if ((startingrod=='A' && endingrod=='C')||(startingrod=='C' && endingrod=='A'));
        {  
            char other = (char)('A' + 'B' + 'C' - startingrod - endingrod) ; 
        System.out.println("OK. Starting with discs 1, 2, 3, on rod " + startingrod + "\n");
        System.out.println("Moves are:");
        playHanoi (3,startingrod,other,endingrod);
        //index++; 
        System.out.println();
        System.out.println("All done.");
        System.out.println("Took a total of " + (count - 1) + " moves.");
        sc.close();

        System.out.println();
        }   
    }
    private static void playHanoi( int n, char from , char other, char to)
    { 
        // int count = 1;
        if (n == 0)  
            return;
        else if(n == 1)
  
        { 
            System.out.printf("%d. " + "Move disk "+ n +" from rod %c to rod %c \n", /*index*/ count, from, to);
            //index++;
            count++;
            // return count;         
        }      
        else
        { 
            playHanoi(n - 1, from, to, other);  
            System.out.printf("%d. " + "Move disk " + n + " from rod %c to rod %c \n", /*index*/ count, from, to);
            count++;
            playHanoi(n - 1, other, from, to);
            //index++;
            // return count;
        }    
        return;
    }
}

The only case you handled in the previous code is when starting rod is A and ending index is C.


Related Solutions

I have a recursive Tower of Hanoi program and would like to get the index numbers...
I have a recursive Tower of Hanoi program and would like to get the index numbers to be in correct sequence: 1,2,3,4,5,6,7. How can I do this? Main.java import java.io.*; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args){ /**There is a stack of N disks on the first of three poles (call them A, B and C) and your job is to move the disks from pole A to pole C without ever putting a...
There is a famous puzzle called the Tower of Hanoi. Code the recursive implementation of it...
There is a famous puzzle called the Tower of Hanoi. Code the recursive implementation of it with Python.
Write two Java programs ( Iterative and Recursive programs ) that solves Tower of Hanoi problem?use...
Write two Java programs ( Iterative and Recursive programs ) that solves Tower of Hanoi problem?use 4 disks and 3 bars
Java program that uses binary tree and recursions to implement Tower of Hanoi game where there...
Java program that uses binary tree and recursions to implement Tower of Hanoi game where there can be any amount of disks and there are either 3,4, or 5 pegs to store the disks(# of pegs and disks is manually inputted by user), in Tower of Hanoi game, the object of the game is move all the pieces from the 1st peg to the right most peg or the opposite side. You can place disks on top of each other...
Write a MIPS assembly program to calculate the Fibonacci numbers from 1..n using the recursive method....
Write a MIPS assembly program to calculate the Fibonacci numbers from 1..n using the recursive method. The definition of a Fibonacci number is F(n) = F(n-1) + F(n-2). The implementation must follow the following guidelines: Prompt the user for a number n Allocate heap memory to hold the exact number of elements in the Fibonacci sequence for n Implement recursive Fibonacci method as a subprogram Print the Fibonacci sequence array
My balance sheet does not balance please correct the missing information from trial balance and correct...
My balance sheet does not balance please correct the missing information from trial balance and correct the balance sheet below. 2016 Dr Cr Accounts Payable       1,079,837 Accounts Receivable      3,245,967 Accrued Liabilities - Other          721,358 Accrued Pension Liabilities          450,356 Accrued Restructuring Charges            90,476 Accrued Salaries, Wages and Commissions          350,191 Accumulated Other Comprehensive Income (Loss)            85,000 Accumulated Depreciation - Property, Plant & Equipment       1,999,999 Accumulated Post-Employment Benefit Obligation (long-term)          402,634 Additional Paid-in Capital,...
​Write a recursive method, vowels, that returns the number of vowels in a string. Also, write a program to test your method.
Write a recursive method, vowels, that returns the number of vowels in a string. Also, write a program to test your method.(JAVA Code)
How do I get my program to ask the user to re enter the correct information...
How do I get my program to ask the user to re enter the correct information if the information entered does not match the database records? When I run my program it does let me know that the information entered does not match the database records but it does not ask me to enter the information again. Please add code (in bold) in the proper area with short explanation package MailMeSQL; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import...
How do I get my program to ask the user to re enter the correct information...
How do I get my program to ask the user to re enter the correct information if the information entered does not match the database records? When I run my program it does let me know that the information entered does not match but it does not ask me to enter the information again. package MailMeSQL; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; import com.mysql.cj.jdbc.JdbcConnection; public class mailmeMain {    public static void...
This program does password verification. It gives the user three attempts to type in the correct...
This program does password verification. It gives the user three attempts to type in the correct password. Assume that the password is "COMSC110" (You can hard-code this). If the user types in the correct password, display a message saying "Login successful" and break out of the loop, otherwise display " Login Failed" and go to the next iteration. If the user enters three unsuccessful entries, then display a message saying " Too many attempts, Try again later", Use a while...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT