Pedro
Pedro

Reputation: 19

Recursive method in Java is not working. Any ideas?

I am trying to understand the recursive methods in Java and tried this simple method to calculate a factorial. Somehow it doesn't work. Can someone tell me why?

public class FactorialRecursive extends ConsoleProgram {

   public void run() {
      println("This program calculates the factorial of an integer n.");
      int n = readInt("Please insert n: ");
      int result = factorial(n);
      println("The factorial of " + n + " is " + result);
   }

   private int factorial(int n) {
      int total;
      if (n == 1) total = 1;
      total = n * factorial(n - 1);
      return (total);
   }
}

Upvotes: 1

Views: 2169

Answers (4)

Mik378
Mik378

Reputation: 22171

Replace the line:

if (n==1) total = 1;

by:

if (n==1) return 1;

Otherwise, you'll loop infinitely.

Your method would be:

private int factorial(int n) {
    return n==1 ? 1 : n * factorial (n-1);
}

Upvotes: 2

UmNyobe
UmNyobe

Reputation: 22890

The issue is that you dont stop when you find your base case

 if (n==1) total = 1;

Rather do

 if (n==1) return 1;

Upvotes: 2

Andreas Fester
Andreas Fester

Reputation: 36630

You are not terminating your recursion. Try

if (n==1) total = 1;
else total = n * factorial (n-1);

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

This is because your base case (n == 1) does not return right away.

You only assign total, but do not return: instead, you go with n * factorial(n-1) again, entering into infinite recursion.

Fix by replacing with

if (n==1) return 1;

or adding an else:

if (n==1) total = 1;
else total = n * factorial (n-1);

Upvotes: 4

Related Questions