我目前正在学习Java的入门课程,这是关于try-catch方法的。当我输入这段代码时,我的System.out.println语句会无休止地重复。下面是我的代码:
public static double exp(double b, int c) {
if (c == 0) {
return 1;
}
// c > 0
if (c % 2 == 0) {
return exp(b*b, c / 2);
}
if (c<0){
try{
throw new ArithmeticException();
}
catch (ArithmeticException e) {
System.out.println("yadonegoofed");
}
}
// c is odd and > 0
return b * exp(b, c-1);
}发布于 2012-04-13 08:57:34
if (c<0){
try{
throw new ArithmeticException();
}
catch (ArithmeticException e) {
System.out.println("yadonegoofed");
}
}
// c is odd and > 0
return b * exp(b, c-1);您的注释c is odd and > 0不正确--您实际上从未使用异常终止函数。您抛出它,立即捕获它,然后继续执行递归函数。最终,当您点击wraparound时,它将再次成为正数,并且错误不会发生。(还有大约20亿次迭代--别等了。)
我不会在这里使用异常--您只需要终止递归。在检查0之前,我会先检查负输入,然后在那里抛出异常,然后在调用者中捕获异常。
在伪代码中:
exp(double b, int c) {
if (c < 0)
throw new Exception("C cannot be negative");
} else if (c % 2 == 0) {
return exp(b*b, c / 2);
} else {
/* and so forth */
}
}发布于 2012-04-13 09:05:37
当涉及到创建自己的自定义异常时,您忘记了一个非常重要的部分。您忘了告诉该方法它将抛出这样一个方法。您的第一行代码应如下所示:
public static double exp(double b, int c) throws ArithmeticException {注意,我已经亲自测试过了,它只会在您的输出中抛出一次异常。
发布于 2012-04-13 08:57:27
例如,如果c= -1 in,则第一个和第二个If失败,第三个if抛出异常,然后打印错误,但由于您处理了excpetion,所以事情继续进行。所以它调用exp(b,-2)。反过来,在返回中调用exp(b,-3),依此类推。将C的值添加到println以进行验证。
https://stackoverflow.com/questions/10133905
复制相似问题