0

Why isn't this working?!? I'm writing a function that simplifies a square root (i.e sqrt(44) would turn into 2*sqrt(11). I'm returning this as a double[] but I'm getting an error that says "This method must return a result of type double[]" even though I am returning a double[]. Can anyone please let me know how to fix this, I'm completely lost.

public static double[] simpDiscr(double d, double coeff) {
    int max = (int) (Math.floor(Math.sqrt(d)));
    int[] squares = {};
    for (int i = 2; i <= max; i++) {
        squares = Arrays.copyOf(squares, squares.length + 1);
        squares[squares.length - 1] = i * i;
    }
    for (int square : squares) {
        if (d / square == Math.floor(d / square)) {
            d = d / square;
            coeff = coeff * Math.sqrt(square);
            return simpDiscr(d, coeff);
        } else {
            double[] dAndCoeff = { d, coeff };
            return dAndCoeff;
        }
    }
}
johnjuly
  • 1
  • 2

1 Answers1

0

You have an if-else inside the for loop which returns on both cases. This means the for loop will never reach the second iteration. This seems to be a bug.

The compiler however complains that you need to return a value on all code paths, meaning it could be that there are no items in squares, and what would the method return after the for loop? You need to add a return statement after the loop.

Sebastian
  • 5,177
  • 4
  • 30
  • 47