Skip to content
Advertisement

Why is function not returning array in Java?

I’m making a small script to calculate the Fibonacci sequence by having an array to give how many digits i want, I just can’t figure out why my fib function is saying that there is no array being returned.

Code:

class Fibonacci{
    public static void main(String[] args){
        int[] startArray = {1,1,0,0,0,0,0,0,0,0};
        int[] resultArray = fib(startArray);
        
        System.out.println("Iterative Ausgabe des Fibonacci-Arrays:");
        printIterativ(resultArray);
        
        System.out.println();
        
        System.out.println("Rekursive Ausgabe des Fibonacci-Arrays:");
        printRekursiv(resultArray);
    }
    
    public static int[] fib(int[] array){
        for(int i=0;i<array.length;i++){
            array[i+1] = array[i] + array[i-1];
        return array;
        }
    }
    
    public static void printIterativ(int[] array) {
        System.out.println(array);
    }

    public static void printRekursiv(int[] array) {
        for(int i=0;i<array.length;i++){
            System.out.println(array[i]);
        }
    }
}

Advertisement

Answer

 public static int[] fib(int[] array){
        for(int i=0;i<array.length;i++){
            array[i+1] = array[i] + array[i-1];
        return array;
        }
    }

It’s a matter of scopes. Your only return statements is within the for loop, but if your for loop never executes, there is no return statement.

So:

 public static int[] fib(int[] array){
        for(int i=0;i<array.length;i++){
            array[i+1] = array[i] + array[i-1];
        return array;
        }
    return array;
    }

or

 public static int[] fib(int[] array){
        for(int i=0;i<array.length;i++){
            array[i+1] = array[i] + array[i-1];
        }
        return array; 
    }

would work, because they have return statements for all scenario’s. You’ll need to figure out which one meets your requirements. But, since you don’t actually call fib anywhere, you might also delete the method.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement