Home Tutorials Training Consulting Products Books Company Donate Contact us









Online Training

Quick links

Share

Towers of Hanoi in Java. This article describes how to solve the Towers of Hanoi in Java.
-->

2. Implementation in Java

Create a Java project "de.vogella.algorithms.towersofhanoi".

Create the following program.

package de.vogella.algorithms.towersofhanoi;

/**
 * Towers of Hanoi
 * Pole are labeled 1, 2,3
 * Each disk is also labeled
 * @author Lars Vogel
 *
 */
public class TowersOfHanoi {
    public static void move(int n, int startPole, int endPole) {
        if (n== 0){
            return;
        }
        int intermediatePole = 6 - startPole - endPole;
        move(n-1, startPole, intermediatePole);
        System.out.println("Move " +n + " from " + startPole + " to " +endPole);
        move(n-1, intermediatePole, endPole);
    }

    public static void main(String[] args) {
        move(5, 1, 3);
    }


}
-->

Copyright © 2012-2018 vogella GmbH. Free use of the software examples is granted under the terms of the Eclipse Public License 2.0. This tutorial is published under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Germany license.

See Licence.