河内塔,停止滑动 [英] Tower of Hanoi, stop sliding
问题描述
我为河内塔问题开发了解决方案:
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?
更新:结果为6张幻灯片,但应为5张 http://ideone.com/lm084
推荐答案
正题:
在我看来,好像 counter
没有在任何地方定义,因此不应编译.
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
在这种情况下,当c == 0
和h == 1
发生异常.
The exception will occur when c == 0
and h == 1
, in that case.
离题:这些行:
Integer n = Integer.parseInt(args[0]);
Integer k = Integer.parseInt(args[1]);
应该是
int n = Integer.parseInt(args[0]);
int k = Integer.parseInt(args[1]);
...因为parseInt
返回int
(不是Integer
),并且您要传递给它们的函数接受int
(不是Integer
).自动装箱可能会让您摆脱困境,但这是不必要的.
...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.
这篇关于河内塔,停止滑动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!