2016-07-14 64 views
0

我正在尝试解决一个基本的练习(计算阶乘),但我陷入了一个错误。在IntelliJ中使用递归方法的因子

我在的IntelliJ工作

代码:

public class calculation { 

    public long factorial(long number) { 
     if (number <= 0) { 
      return 1; 
     } 
     else 
      return number * factorial(number - 1); 

    } 
} 

    public static void main(String[] args) { 

     for(int counter = 0; counter <= 21; counter++) 
     { 
      System.out.printf("%d! = %d", counter, factorial(counter)); 
     } 
    } 
} 

错误我收到:

Error:(18, 30) java: class, interface, or enum expected - 4 instances

我也试过用扫描仪读取来自键盘的一个数字,然后调用该函数,但我得到了同样的结果。

在此先感谢。

+3

把你的主要方法的类中。 – Compass

+2

删除else语句后的第二个'}'。 – hexafraction

+0

使用循环来调用像这样的递归方法只有在练习时才有意义。 –

回答

0

你有1个额外的右括号,因为你的void main()超出了类。修复并尝试再次运行代码。下面的代码运行良好。

` 公共类计算{

public static long factorial(long number) { 
    if (number <= 0) { 
     return 1; 
    } 
    else 
     return number * factorial(number - 1); 

} 

public static void main(String[] args) { 

    for(int counter = 0; counter <= 21; counter++) 
    { 
     System.out.printf("%d! = %d", counter, factorial(counter)); 
    } 
} 

}

+0

你需要修复你的格式 – pjs