第五回 の C の実装の構造をそのまま踏襲します.
class Toh06 {
static Stack[] pegs = new Stack[3];
static int N, w;
static String ws = "", bar = "", grnd = "";
static void print()
throws InterruptedException
{
int i, j, k;
Thread.sleep(w);
System.out.print("\u001b[2J\u001b[2;1H");
for (i = 0; i < N; i++) {
for (j = 0; j < 3; j++) {
if (pegs[j].depth < N - i)
System.out.print(" " + ws + "|" + ws + " ");
else
System.out.print(
" " +
ws.substring(pegs[j].data(N - i - 1)) +
bar.substring(N - pegs[j].data(N - i - 1)) +
"|" +
bar.substring(N - pegs[j].data(N - i - 1)) +
ws.substring(pegs[j].data(N - i - 1)) +
" ");
}
System.out.println("");
}
System.out.println(grnd);
}
static void move(Stack src, Stack tmp, Stack dst, int n)
throws InterruptedException
{
if (n == 0)
return;
move(src, dst, tmp, n - 1);
dst.push(src.pop());
print();
move(tmp, src, dst, n - 1);
}
public static void main(String[] args)
throws InterruptedException
{
int i;
/*
* init
*/
N = (args.length < 1)?3:Integer.parseInt(args[0]);
w = (args.length < 2)?500:Integer.parseInt(args[1]);
pegs[0] = new Stack(N);
pegs[1] = new Stack(N);
pegs[2] = new Stack(N);
for (i = 0; i < N; i++)
pegs[0].push(N - i);
/*
* for display
*/
for (i = 0; i < N; i++)
ws += " ";
for (i = 0; i < N; i++)
bar += "-";
for (i = 0; i < 6*N + 9; i++)
grnd += "=";
/*
* do
*/
print();
move(pegs[0], pegs[1], pegs[2], N);
}
}
class Stack {
int depth;
int[] _data;
Stack(int n) { _data = new int[n]; depth = 0; }
void push(int data) { _data[depth] = data; depth++; }
int pop() { depth--; return _data[depth]; }
int depth() { return depth; }
int data(int position) { return _data[position]; }
}
スタックを (java.util.Stack は使わず) 内部クラスで定義.
この規模ではオブジェクト指向の良さは特に発揮できないかもしれませんが, もう少し整理された書き方ができるとは思います.
他の言語と違うところは. ファイル名とクラス名を一致させないといけないところです.
上記コードを Toh06.java として保存する必要があります.

