我正在做河内塔,我想输出所有的招式(2^n-1(,并增加前导空格。例如
Moving top disk from....
Moving top disk from....
Moving top disk from....
Moving top disk from....
等等
我试图创建一个单独的";空间";方法,但我不确定如何将其实现到程序中
这是我现在代码的一部分。
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);
}
我使用了一个字符串生成器来实现缩进。缩进的数量由类"的静态变量定义;凹痕";每次调用moveDisk方法时都会使用for循环。
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);
}
}
结果:
Moving top disk from 10 to 10
Moving top disk from 1 to 10
Moving top disk from 20 to 10
您可以通过Apache Commons Framework进行import org.apache.commons.lang3.StringUtils
。
然后使用:
StringUtils.leftPad("123456", tab_length * 2)
//or however you want to format the left space
这是最方便的方法,否则,您可以使用StringBuilder或类似的东西编写自定义的leftPad方法。