(Java) Tower of Hanoi

Posted: July 31, 2008 in Java, Programming
Tags: ,

He he he..now, i make Tower of Hanoi in Java Language, if you want more explanation about what is Tower of Hanoi, click HERE.

import java.util.Scanner;

public class Main 
{
         
    public static void main(String[] args)
    {
        Scanner S=new Scanner(System.in);
        int x;
        char from='A', to='B', help='C';

        do{
            try
            {
                System.out.println("  input number of disk: ");
                x = Integer.parseInt(S.nextLine());
            }
            catch (NumberFormatException e)
            {
                x = -10;
            }
        }while(x==-10 || x>10);
        
        System.out.println("n  from = A, to = B, help = Cn");
        hanoi(x, from, to, help);
    }

    static void hanoi(int x, char from, char to, char help)
    {
        if (x > 0)
        {
            hanoi(x - 1, from, help, to);
            move(x, from, to);
            hanoi(x - 1, help, to, from);
        }

    }

    static void move(int x, char from, char to)
    {
        System.out.println("  move disk "+x+" from "+from+" to "+to);
    }

}
Comments
  1. nonot says:

    hoi zer, still blogging? btw nice article there..:P

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s