问题
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
回答1:
On-topic:
It looks to me as though counter
is 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.:
java HanoiNK 5 3
The exception will occur when c == 0
and h == 1
, in that case.
Off-topic: These lines:
Integer n = Integer.parseInt(args[0]);
Integer k = Integer.parseInt(args[1]);
should be
int n = Integer.parseInt(args[0]);
int k = Integer.parseInt(args[1]);
...since parseInt
returns int
(not Integer
) and the function you're passing them into accepts int
(not Integer
). Auto-boxing probably lets you get away with it, but it's unnecessary.
回答2:
I think counter == c
? Therefore try too move c--;
above your bewege(c, h - 1, ablage, quelle, ziel);
and it should work, so it looks like this:
public static void bewege(int c, int h, char quelle, char ablage, char ziel)
throws Exception{
if(h > 0){
if(c != 0){
c--;
bewege(c, h - 1, quelle, ziel, ablage);
System.out.println("Move "+ h +" from " + quelle + " to " + ziel);
c--;
bewege(c, h - 1, ablage, quelle, ziel);
}else{
throw new Exception("stop sliding");
}
}
}
回答3:
I'm not sure where the counter
variable is declared (doesn't seem to be here), but you're not decrementing it anywhere, so it's value will never change.
来源:https://stackoverflow.com/questions/4570685/tower-of-hanoi-stop-sliding