Home > Software design >  this method must return a result type of int
this method must return a result type of int

Time:06-04

public class egehanx1 {

    public static void main(String[] args) {
        int[] A = { 5, 2, 3 };

        System.out.println((splitIndex(A)));
    }

    public static int splitIndex(int[] A) {
        double sum = 0, halfsum = 0, size = A.length;

        for (int i = 0; i < A.length; i  ) {
            sum  = A[i];

        }
        for (int i = 0; i < A.length; i  ) {
            halfsum  = A[i];
            if (halfsum == sum / 2) {
                return A[i];

            }

            else {
                return -1;
            }
        }
    }
}

Hello, I'm getting this error that says this method must return a result type of int,how do i fix this code its a question that asks you to split array in 2 pieces and the sum of them will be same if so print that indexed array element , else print -1

CodePudding user response:

I think suppose the incoming array is empty what should be returned. There is no return statement at the end of function it seems. So the function is expecting some return statement but it couldn't find one for that case and that's why it is showing that error it seems.

public static void main(String[] args) {
        int[] A = { 5, 2, 3 };

        System.out.println((splitIndex(A)));
    }

    public static int splitIndex(int[] A) {
        double sum = 0, halfsum = 0, size = A.length;

        for (int i = 0; i < A.length; i  ) {
            sum  = A[i];

        }
        for (int i = 0; i < A.length; i  ) {
            halfsum  = A[i];
            if (halfsum == sum / 2) {
                return A[i];

            }

            else {
                return -1;
            }
        }

        return -1;
    }

This code works fine without any compilation errors.

CodePudding user response:

In case of the array is empty, your code won't go inside the last loop. This causes your error as the function returns nothing in the case. You should add a return statement after the lase loop, which could probably return -1

  •  Tags:  
  • java
  • Related