2012-06-22 89 views
0
public class MultiplyViaRecursion{ 

    public static void main(String[] args){ 

     System.out.println("8 * 9 == " + multiply(8, 9)); 
     System.out.println("6 * 0 == " + multiply(6, 0)); 
     System.out.println("0 * 6 == " + multiply(0, 6)); 
     System.out.println("7 * -6 == " + multiply(7, -6)); 
    } 

    public static int multiply(int x, int y){ 
     int result = 0; 

     if(y > 0) 
      return result = (x + multiply(x, (y-1))); 
     if(y == 0) 
      return result; 
     if(y < 0) 
      return result = -multiply(x, -y); 

     return result; 
    } 
} 

我的问题很简单和基本,为什么在每个“如果”“返回”仍然无法通过编译,错误显示缺少回报。乘以无乘法,除法和位运算符,并且没有循环。递归

+1

无法重现您的问题。 –

+0

他发布了编译的代码;他问为什么如果他删除了编译器失败的最后一个'return'语句。 – cheeken

回答

1

因为编译器无法猜测你的三个IF覆盖了所有的情况。 如果要简化代码,你可以删除最后,如果这是不必要的:

public static int multiply(int x, int y){ 
    int result = 0; 
    if(y > 0) 
     return result = (x + multiply(x, (y-1))); 
    if(y == 0) 
     return result; 
    return result = -multiply(x, -y); 
} 

顺便说一句,你还可以删除result变量:

public static int multiply(int x, int y){ 
    if(y > 0) 
     return (x + multiply(x, (y-1))); 
    if(y == 0) 
     return 0; 
    return -multiply(x, -y); 
} 
+0

是的,谢谢,非常有帮助 – lxx22

6

简单地说: Java编译器不是那么聪明。它不能推断出你的三个if陈述中的一个必须评估为真。由于编译器认为有可能所有的条件都失败,它认为有可能超出if块,此时没有return语句。

而是尝试使用if else块,就像这样。

public static int multiply(int x, int y) { 
    int result = 0; 

    if (y > 0) 
     return result = (x + multiply(x, (y - 1))); 
    else if (y == 0) 
     return result; 
    else 
     return result = -multiply(x, -y); 
}