Search code examples
javaarraysfactorial

Calculating the factorial of every element in an integer array


I need to create a Method that has 2 parameters in Java, upperborder and lowerborder. This method must create an array from the number 2 to the number 10.
Then I must implement another method, that calculates the factorial for a given number.
Then I must implement a third method that calculates the factorial for every element in the created array and test all these methods in a TestClass.

I know how to do this, but apparently I'm making some kind of a mistake in my code and it gives me the StackOverflow exception. I read the code a couple of times, but I can't seem to quite understand where I'm wrong.

package fakultaetinarray;


public final class FakultaetinArray{
    private int i;
    private int[] a;
    private int j;

    public FakultaetinArray(){
        System.out.println("Given array : ");
        createArray(1, 9);
        System.out.println("Factorial for every element : ");
        FakinArray();

    }
    public int fakRe(int n){
        if(n == 1){
            return n;
        }
        return n * fakRe(n - 1);
    }
    public void createArray(int untergrenze, int obergrenze){
        this.a = new int[obergrenze];
        for(this.j = 1; j <= a.length; j++){
            a[i] = j + 1;
            System.out.println(a[i]);
        }
    }
    public void FakinArray(){
        a[0] = 2;
       for(i = 1; i < a.length; i++){
          int fak = fakRe(a[i]);
          a[i] = fak;
          System.out.println(fak);

       }

    }

}

Solution

  • The reason you're getting StackOverflowErrors is due to your recursive method not having a case when n == 0.

    The reason that your values are coming in as 0 is due to how you're constructing your loop.

    for(this.j = 1; j <= a.length; j++){
        a[i] = j + 1;
        System.out.println(a[i]);
    }
    

    It's unclear why you're using j here at all, and i is initialized to its default value of 0, so in all reality, you're only ever filling one element of your array with a positive value and all of the others are at zero.

    You need to reconsider how your loops are constructed. I would strongly encourage you not to make them fields, but declare them as part of the loop construct instead.