0

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

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);
 }
}

它工作正常。现在我想限制幻灯片的数量并在达到某个限制时抛出异常。我用计数器尝试过,但它不起作用:

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");
   }
  }
 }
}

永远不会抛出异常。有任何想法吗?

更新:结果是 6 张幻灯片,但应该是 5 张 http://ideone.com/lm084

4

3 回答 3

1

主题:

在我看来,好像counter没有在任何地方定义,所以不应该编译。

现在您已经编辑了您的问题以解决上述问题,如果您的第一个参数大于您的第二个参数,则会引发异常,例如:

java HanoiNK 5 3

在这种情况下,当c == 0和时会发生异常h == 1


题外话:这些行:

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(not Integer) 并且您将它们传递给的函数接受int(not Integer)。自动装箱可能会让你摆脱它,但它是不必要的。

于 2010-12-31T14:50:37.110 回答
1

我想counter == c?因此,尝试移动c--;到您的上方bewege(c, h - 1, ablage, quelle, ziel);,它应该可以工作,所以它看起来像这样:

 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");
        }
    }
}
于 2010-12-31T14:52:10.020 回答
0

我不确定counter变量在哪里声明(似乎不在这里),但你没有在任何地方递减它,所以它的值永远不会改变。

于 2010-12-31T14:53:09.850 回答