Kam*_*roe -3 java recursion trace if-statement
递归调用将在运行时堆栈上构建,然后在运行时堆栈"展开"时以相反的顺序计算值.第18行是我得到错误的地方,但我对于出了什么问题一无所知.编译完成.未编译以下文件:找到1个错误:[line:18]} else {错误:'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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
你得到了,因为你的if语句在一个额外的块中被破坏了.
更改
{
int temp;
if (n==0)
{
return 1;
}
}
else
Run Code Online (Sandbox Code Playgroud)
至
int temp;
if (n==0) {
return 1;
} else ...
Run Code Online (Sandbox Code Playgroud)
你还应该删除额外的声明int temp;.它在您的factorial方法中出现两次.
| 归档时间: |
|
| 查看次数: |
154 次 |
| 最近记录: |