Compile time error

exercise No. 276

Q:

We consider:

/**
 * Get the largest of three values
 *
 * @param a First value
 * @param b Second value
 * @param c Third value
 * @return The maximum of a, b and c
 */
public static int max (int a, int b, int c) {
  if (a < b) {
    if (b < c) {
      return c;
    } else {
      return b;
    }
  } else {
    if (a < c) {
      return c;
    }
  }
}
  1. This code contains three return statements. Nonetheless the compiler echoes a »Missing return statement«. Why ?

  2. Correct both syntactical and logical errors.

A:

  1. In case both a > b and a > c hold, no return statement will be reached. This is an error: A method having a non-void return type must under all circumstances return a value.

  2. We reorganize a little bit:

    public static int max (int a, int b, int c) {
        if (a < b | a < c) { // Either b or c will be the desired maximum
            if (b < c) {
                return c;
            } else {
                return b;
            }
        } else {
            return a;
        }
    }