Home > Back-end >  How can I fix the error "This method must return a result of type int" without breaking th
How can I fix the error "This method must return a result of type int" without breaking th

Time:10-16

As far as I know, I understand this error. I know that within my program there is a situation where no conditions are met and the computer doesn't know what to do. That being said, I'm not sure how to fix it properly without breaking the current code. I've added a return 0 at the end of all the if statements, which gets rid of the error, but in some cases the 0 prints out which of course I don't want it to. I also tried putting it within an else statement at the very end as-well, but I still get the same error.

Assignment instructions are as follows: "If the two parameters are within 1 of each other, return the smaller number; Otherwise, subtract one from the larger parameter and add one to the smaller parameter and balance the result."

Here is what I have:

    public static int balance (int x, int y) {
        if(x == y) {
            System.out.println("The values X and Y ("   x    " and "   y   ") are already balanced; They are equal to each other!");
        }
        
        else if(Math.abs(x-y) == 1) { //Checks to see if numbers are within 1 of each other (Math.abs because negative numbers don't matter in this case)
            if(x > y) {
                return y;
            }
            else return x;
        }
        else if(x > y) {
            x = x - 1; //X is larger so we subtract
            y = y   1; //Y is smaller so we add
            return balance(x,y); //Recursion happens
        }
        else if(x < y) {
            y = y - 1; //Y is larger so we subtract
            x = x   1; //X is smaller so we add
            return balance(x,y); //Recursion happens
        }
    }

The calculations and everything on that side seem to work exactly like the instructions are asking. I just can't seem to get rid of the "This method must return a result of type int" error without having random values that are unneeded showing up in the console.

CodePudding user response:

You need to make two changes.

  1. Decide what to return in the case where x == y, and add the appropriate return statement to the first branch.

  2. Change else if (x < y) { to else {. You know that you've exhausted all the possibilities, but the compiler doesn't. This is a sure-fire way of telling the compiler that there's nowhere else to end up.

Unless you do these two things, the compiler believes there's a possibility that it could run out of lines to execute in the method, without encountering a return statement. That's not valid for a method that you've declared as returning an int.

  • Related