Nicholas Ma
Nicholas Ma

Reputation: 27

Recursion: Factorial

public class Factorial {

    int fact (int n) {

        int result; 

        if (n==1 ||n==0) 
            return 1;

        else 
            result = n*fact(n-1);
        return result;
    }

Assuming n is less than 0 (-1, -2, etc) and the factorial value of these values are "Not valid" (I want the system to print out "Not valid" if the input value (n) is less than 0. How do I modify the code. I understand the method only returns a integer value and not String.

Upvotes: 0

Views: 165

Answers (3)

Yev
Yev

Reputation: 321

I want the system to print out "Not valid" if the input value (n) is less than 0

You can do this by adding

if (n < 0) {
    System.out.println("Not valid");
}

at the beginning of the method. The String "Not valid" will not be returned by the method, but it will be printed out.
After that it would be meaningful to exit the method without further calculation. You can do this according to your needs in either of following ways:

If your programm can do more then just calculating a factorial and you need in any case a return value:

 if (n < 0) {
     System.out.println("Not valid");
     return -1; // or some other inapplicable for a factorial result integer value
 }

or you could also just "hard exit" the whole programm whitout returning any value like

if (n < 0) {
     System.out.println("Not valid");
     System.exit(1); // 1 or any other nonzero integer value 
                     // to tell the system it exits with an error. 0 otherwise
 }

Upvotes: 1

beastlyCoder
beastlyCoder

Reputation: 2401

As @Saravana said, you must add a throws statement that looks something like this:

    int factorial (int n) 
    {
        if (n < 0) 
        {
            throw new IllegalArgumentException("Sorry value cannot be negative");
        }

        if (n==1 || n==0) 
        {
            return 1;
        }
        else 
        {
            return n * fact(n-1);
        }
    }

If any value less than zero there will be an error saying that the user did not enter the value correct. Hope this helped! :)

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521339

Just add an if statement checking for negative input. A factorial should never return negative, so you can return -1 to indicate an error:

int fact (int n) {
    if (n < 0) {
        return -1;
    }

    if (n==1 || n==0) {
        return 1;
    }
    else {
        return n * fact(n-1);
    }
}

Upvotes: 1

Related Questions