河内塔,停止滑动

编程入门 行业动态 更新时间:2024-10-22 17:27:31
本文介绍了河内塔,停止滑动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我为河内塔问题开发了解决方案:

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张 ideone/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.

更多推荐

河内塔,停止滑动

本文发布于:2023-11-30 03:13:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648536.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:河内

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!