java继续接收“else”而没有“if”错误
递归调用将建立在运行时堆栈上,然后在运行时堆栈“展开”时按相反顺序计算值。第18行是我得到错误的地方,但我对什么是错误一无所知。汇编完成。未编译以下文件: 发现1个错误: [行:18]}其他{ 错误:“else”不带“if”
public class Recursion {
public static void main(String[] args) {
int n = 7;
//Test out the factorial
System.out.println(n + " factorial equals ");
System.out.println(Recursion.factorial(n));
System.out.println();
}
public static int factorial(int n) {
int temp;
System.out.println("Method call -- calculating Factorial of: " + n);
{
int temp;
if (n == 0) {
return 1;
}
} else {
temp = factorial(n - 1);
System.out.println("Factorial of: " + (n - 1) + " is " + temp);
return (temp * n);
}
}
}
# 1 楼答案
你得到它是因为你的if语句在一个额外的块中被调用了
改变
到
您还应该删除
int temp;
的额外声明。它在factorial
方法中出现两次