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(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");
}
}
}
}
The exception is never thrown. Any ideas?
UPDATE: result is 6 slides but it should be 5 http://ideone.com/lm084
On-topic:
It looks to me as thoughcounteris not defined anywhere, and so that shouldn’t compile.Now that you’ve edited your question to fix the above, the exception will be thrown if your first argument is greater than your second argument, e.g.:
The exception will occur when
c == 0andh == 1, in that case.Off-topic: These lines:
should be
…since
parseIntreturnsint(notInteger) and the function you’re passing them into acceptsint(notInteger). Auto-boxing probably lets you get away with it, but it’s unnecessary.