The objective of the assignment is to model the puzzle Towers of Hanoi using Obj
ID: 3776226 • Letter: T
Question
The objective of the assignment is to model the puzzle Towers of Hanoi using Object Oriented Programming (Java) and recursion.
There have to be 3 classes:
Disk.java
- Fields: An integer representing the size (width) of the disk
- Methods: A get and set method for the size of the disk
- Constructor: A constructor is called when creating a new instance of the Disk.
Rod.java
- Fields: A collection to store the disks
- Methods: getDisk() and addDisk() methods to return the top disk from the rod and add a disk to top of the rod. Also a method to return the contents of the rod toString().
- Constructor: Creates a rod with n number of disk
Hanoi.java
- Fields: The hanoi class should hold 3 rods
- Constructor: It creates a rod with n number of disks accepted from the user
- Methods: printStatus() to show the contents of the game status after every move. move() to move disk from one rod to another and recursiveTOH(), which will find the solution to the Towers of Hanoi puzzle recursively.
The program should start by asking the user to enter the number of disks on the source rod. For every move show the status of each of the rod and which disk were moved from one rod to another.
*Make sure this puzzle is solved with classes and interesection*
Explanation / Answer
import java.util.*;
/* Class TowerOfHanoiUsingStacks */
public class TowerOfHanoiUsingStacks
{
public static int N;
/* Creating Stack array */
public static Stack<Integer>[] tower = new Stack[4];
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
tower[1] = new Stack<Integer>();
tower[2] = new Stack<Integer>();
tower[3] = new Stack<Integer>();
/* Accepting number of disks */
System.out.println("Enter number of disks");
int num = scan.nextInt();
N = num;
toh(num);
}
/* Function to push disks into stack */
public static void toh(int n)
{
for (int d = n; d > 0; d--)
tower[1].push(d);
display();
move(n, 1, 2, 3);
}
/* Recursive Function to move disks */
public static void move(int n, int a, int b, int c)
{
if (n > 0)
{
move(n-1, a, c, b);
int d = tower[a].pop();
tower[c].push(d);
display();
move(n-1, b, a, c);
}
}
/* Function to display */
public static void display()
{
System.out.println(" A | B | C");
System.out.println("---------------");
for(int i = N - 1; i >= 0; i--)
{
String d1 = " ", d2 = " ", d3 = " ";
try
{
d1 = String.valueOf(tower[1].get(i));
}
catch (Exception e){
}
try
{
d2 = String.valueOf(tower[2].get(i));
}
catch(Exception e){
}
try
{
d3 = String.valueOf(tower[3].get(i));
}
catch (Exception e){
}
System.out.println(" "+d1+" | "+d2+" | "+d3);
}
System.out.println(" ");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.