Hanoi Example
This is a basic Hanoi example
/* * This is a simple Hanoi program */ import java.io.*; /** * * @author JJ */ public class Hanoi { static int numDisks = 3; static int move = 0; public static void main(String[] args) { //Calls the move disks method, passing 4 parameters moveDisks(numDisks, 'A', 'B', 'C'); try { //Create a hanoi text file if it doesn't exists, append text to the file FileWriter fw = new FileWriter("Hanoi.txt", true); PrintWriter pw = new PrintWriter(fw); //Write the total moves to the file pw.println("\nTotal moves " + move); //Close the file pw.close(); } catch(Exception e) { } } //This is the move disk method that calls itself recursively static void moveDisks(int numDisks, char from, char to, char middle) { if(numDisks>=1) { moveDisks(numDisks-1, from, middle, to); getDisks(from, to); moveDisks(numDisks-1, middle, to, from); } } //Here we move the disks static void getDisks(char from, char to) { try { //Create a hanoi text file if it doesn't exists FileWriter fw = new FileWriter("Hanoi.txt", true); PrintWriter pw = new PrintWriter(fw); move++; if(numDisks <=3) { //Pritns the moves to the text file pw.println("from " + from + " to " + to); /* * A series of if statement to determine how many disks are still left in the stack */ if(move==1) { pw.println("\nA = 2 " + " B = 1 " + " c = 0\n" ); } if(move==2) { pw.println("\nA = 1 " + " B = 1 " + " c = 1\n"); } if(move==3) { pw.println("\nA = 1 " + " B = 0 " + " c = 2\n"); } if(move==4) { pw.println("\nA = 0 " + " B = 1 " + " c = 2\n"); } if(move==5) { pw.println("\nA = 1 " + " B = 1 " + " c = 1\n"); } if(move==6) { pw.println("\nA = 1 " + " B = 2 " + " c = 0"); } if(move==7) { pw.println("\nA = 0 " + " B = 3 " + " c = 0"); } } else { pw.println("from " + from + " to" + to); } pw.close(); } catch(Exception e) { } } }
< Java > <Home>< Java Programs >