SamR
SamR

Reputation: 543

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?

Upvotes: 0

Views: 770

Answers (5)

Aniket Inge
Aniket Inge

Reputation: 25705

// Calculate the factorial value
private static int getFactorial(int userInput){
    int ans = userInput;
    if(userInput >1 ){

    ans*= (getFactorial(userInput-1));

    //System.out.println("The value of "+ b +"! is "+ ans);
    }
    return ans;
}

public static void main(String[] args)
{
    int ans;
    //get input
    ans = getFactorial(input);
    System.out.println("The value of "+ b +"! is "+ ans);
}

Upvotes: 0

Alexis King
Alexis King

Reputation: 43852

Instead, call your method from another one and only print the final value:

System.out.println(getFactorial(5));

If you really need to do it from inside the method you can create a sort of "trampoline" method, like so:

private static int getFactorial(int userInput) {
    int fact = _getFactorial(userInput);
    System.out.println(fact);
    return fact;
}

private static int _getFactorial(int userInput) {
    // real implementation
}

Upvotes: 1

Ted Hopp
Ted Hopp

Reputation: 234795

Since you don't like the idea of just returning a value and printing from the caller code, you can add a "print the answer" flag as an argument:

// Calculate the factorial value
private static int getFactorial(int value, boolean print){
    if (value > 1) {

        value *= getFactorial(value-1, false);

        if (print) {
            System.out.println("The value of "+ b +"! is "+ value);
        }
    }
    return value;
}

Personally, though, I'd prefer the "trampoline method" of Jake King's answer.

Upvotes: 0

sravanreddy001
sravanreddy001

Reputation: 257

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

Upvotes: 0

rbhawsar
rbhawsar

Reputation: 813

// Calculate the factorial value
private static int getFactorial(int userInput){
    int ans = userInput;
    if(userInput >1 ){

    ans*= (getFactorial(userInput-1));

    }

     return ans;
}

and print outside the function

System.out.println("The value of "+ b +"! is "+ getFactorial(b));

Print only once, when you got the final answer.

Upvotes: 0

Related Questions