Tower of Hanoi, stop sliding
- by ArtWorkAD
Hi,
I developed a solution for the Tower of Hanoi problem:
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);
}
}
It works fine. Now i want to limit the number of slides and throw an exception if a certain limit is reached. I tried it with a counter but it does not work:
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(counter != 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");
}
}
}
}
The exception is never thrown. Any ideas?