简体   繁体   中英

I have a method that returns a int, and it tells me i'm missing a return statement. Can this be fixed without rewriting the method?

This is the method. As you can see, all of the if statements have a return in them so I understand why it is not recognizing the output, but is there any way to fix this?

private int bounds(int x, int y) {
        if (x == -1) {
            if (y == -1) {
                return life[130][70];
            }
            else if (y == 71) {
                return life[130][0];
            }
            if (0 <= y && y <= 70) {
                return life[130][y];
            }
        }
        else if (x == 131) {
            if (y == -1) {
                return life[0][70];
            }
            else if (y == 71) {
                return life[0][0];
            }
            if (0 <= y && y <= 70) {
                return life[0][y];
            }
        }
        if (0 <= x && x <= 130) {
            if (y == -1) {
                return life[x][70];
            }
            else if (y == 71) {
                return life[x][0];

            }
            if (0 <= y && y <= 70) {
                return life[x][y];
            }
        }
    }

Ask yourself what your method would return if x is -2 for example.

Meaning: the compiler tells you that there are paths through that method that don't see a return statement. Simply: believe the compiler.

You could fix the problem by adding one final return statement after your if blocks.

But the real answer: you should never write code that turns that complicated. The above is a maintenance nightmare. It should be refactored.

you need to add a default return to the end of your function, if not one of the if statement is true

It is possible to fix the missing return statement compilation error without rewriting the method by:

  1. Throwing a RuntimeException (if only some inputs are valid).
  2. Returning a default value at the end (if all inputs are valid).

In the existing logic, negative integers other than -1 are not handled (same with upper bounds for x and y). If inputs which are not currently handled are invalid, you may do something like:

private int bounds(int x, int y) {
    ...
    (Existing logic)
    ...
    throw new IllegalArgumentException("Bad input");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM