Search code examples
javamethodsfactorialprintln

Print my recursive factorial result


I need to print my final answer for my method. However, it shows the whole calculation to the end! How can I eliminate the process to get only the result?


Solution

  • This is a recursive function call, which is executed in all the cases without special condition checks. printing from another method is a good option.

    private static int getFactorial(int userInput){
        int ans = userInput;
        if(userInput >1 ){
    
        ans*= (getFactorial(userInput-1));
        }
        return ans;
    
    }
    // New method;
    private static void printFactorial(int userInput){
        System.out.println("The value of " + userInput + "! is " + getFactorial(userInput));
    }