Method that returns the smallest between two parameters does not work

Asked

Viewed 46 times

0

Create a method with two parameters that returns the smaller of two numbers passed as parameters

When I don’t know how to solve, usually I will see the resolution with explanation, but it turns out that this time there was no English translation, only the original in Suomi :/

What is the reason for the function smallest() do not return value?

public class AdaLovelace {
             public static void main(String[] args) {
                  int result = smallest(1, 3);
                  
                  System.out.println(result);
            }
             
             public static int smallest(int n1, int n2){
                 if(n1 > n2){
                     return n2;
                 } else if(n2 > n1){
                     return n1;
                    }
                }
            }

1 answer

4


The function gives error because for the compiler there is situation that may not return a value. You have a condition that checks if one of them is bigger, then checks if the other is bigger, and when it’s equal, you do what? It makes a mistake. You can’t,

It turns out that two things can only happen there if you enter the first condition you must return that, if you don’t enter then you must return to another variable, that’s all, nothing else can happen, then simplifying the code and eliminating the verification that does not make sense because it is already guaranteed that it is the opposite of the other, even if it is equal should return any of the numbers because both are the smallest, besides being the largest also, to facilitate I chose to return the second.

Writing the code in a simpler, more organized way and reversing the signal just to give a more suitable semantics to the code because it asks to find the smallest and reading the code seems to be getting the biggest (not because it has a double inversion, reverses the operator and reverses who is returned), would be like this:

class Main {
    public static void main(String[] args) {
       System.out.println(smallest(1, 3));
    }
    public static int smallest(int n1, int n2) {
        if (n1 < n2) return n1;
        return n2;
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.