javaoutputindentationspacestowers-of-hanoi

How to output indenting strings in Java?


I am doing the Towers of Hanoi and I want to output all the moves (2^n-1) with increasing leading spaces. E.g.

Moving top disk from....
    Moving top disk from....
        Moving top disk from....
            Moving top disk from....

... and so on.

I tried to create a separate "space" method, but I'm unsure as to how to implement it into the program

This is a part of my code right now.

public static void towersOfHanoi(int disk, int source, int dest){
        int temp;
        if (disk == 1) {
            moveDisk(source,dest);
        }
        else {
            temp = 6 - source - dest;
            towersOfHanoi(disk-1,source,temp);
            moveDisk(source,dest);
            towersOfHanoi(disk-1,temp,dest);
        }
    }
    
    private static void moveDisk(int source, int dest) {
        System.out.println("Moving top disk from " + source + " to " + dest);
    }

Solution

  • I have used a string builder to implement the indents. The number of indents are defined by a static variable for the class "indents" and a for loop is used each time the moveDisk method is called.

    public class Test {
    
        static Integer indents = -2;
        static String indent = "   ";
        public static void towersOfHanoi(int disk, int source, int dest){
            int temp;
            if (disk == 1) {
                moveDisk(source,dest);
            }
            else {
                temp = 6 - source - dest;
                towersOfHanoi(disk-1,source,temp);
                moveDisk(source,dest);
                towersOfHanoi(disk-1,temp,dest);
            }
        }
    
        private static void moveDisk(int source, int dest) {
    
            indents = indents + 1;
    
            StringBuilder sb = new StringBuilder();
    
            for(int i = 0; i<=indents; i++){
                sb.append(indent);
            }
            sb.append("Moving top disk from ");
            sb.append(source);
            sb.append( " to ");
            sb.append( dest);
    
            System.out.println(sb.toString());
        }
    
        public static void main(String[] args) {
    
            moveDisk(10, 10);
            moveDisk(1, 10);
            moveDisk(20, 10);
    
        }
    }
    

    The outcome:

    Moving top disk from 10 to 10
       Moving top disk from 1 to 10
          Moving top disk from 20 to 10