ハノイの塔の問題の解決策を開発しました。
public static void bewege(int h, char quelle, char ablage, char ziel) {
if(h > 0){
bewege(h - 1, quelle, ziel, ablage);
System.out.println("Move "+ h +" from " + quelle + " to " + ziel);
bewege(h - 1, ablage, quelle, ziel);
}
}
それは正常に動作します。ここで、スライドの数を制限し、特定の制限に達した場合に例外をスローしたいと考えています。カウンターで試してみましたが、うまくいきません:
class HanoiNK{
public static void main(String args[]){
Integer n = Integer.parseInt(args[0]);
Integer k = Integer.parseInt(args[1]);
try{
bewege(k, n, 'A', 'B', 'C');
}catch(Exception e){
System.out.println(e);
}
}
public static void bewege(int c, int h, char quelle, char ablage, char ziel)
throws Exception{
if(h > 0){
if(c != 0){
bewege(c, h - 1, quelle, ziel, ablage);
c--;
System.out.println("Move "+ h +" from " + quelle + " to " + ziel);
bewege(c, h - 1, ablage, quelle, ziel);
c--;
}else{
throw new Exception("stop sliding");
}
}
}
}
例外がスローされることはありません。何か案は?
更新: 結果は 6 枚のスライドですが、5 枚にする必要があります http://ideone.com/lm084