簡體   English   中英

IntelliJ中的階乘使用遞歸方法

[英]Factorial using recursion method in 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));
        }
    }
}

我收到的錯誤:

錯誤:(18、30)Java:期望類,接口或枚舉-4個實例

我也嘗試使用掃描儀從鍵盤上讀取一個數字,然后調用該函數,但是得到了相同的結果。

提前致謝。

您有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));
    }
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM