Doubt with "Return" in functions (java)

Asked

Viewed 166 times

-3

I have a basic question with the following code:

    public static float calcularMediaAlturaHomens (float TotalAlturaHomens, int NumeroHomens) {
         if (NumeroHomens == 0) {
             return "Sem média!";
         }
         return TotalAlturaHomens / NumeroHomens;
    }

Explanation: My program has a function that calculates the average height of all men (total height / number of men) (according to Return), I would also like that if there were no men registered, it would return "NO AVERAGE" (first Return)but of course the error that I should return a FLOAT value, and not string because the function was created in float. (float calculatorMediaAlturaHomens).

Doubt: How would I return a String inside a float function?

  • 1

    It’s a suggestion because it doesn’t answer the question "How I would return a String within a float function?". Return Double.NAN and the portion of the code responsible for displaying the result that interprets it aided by Double.isNaN().

  • 1

    @Augustovasques is easier to return -1 in his case.

2 answers

3

You probably played with another language (javascript, php, python) which are not strongly typed and then came to Java.

In Java, what you want to do is not possible, but there is a way to do it.

As in Java, everything is an object, you can create an instance of any object and return this instance, but it is a bad practice.

 public static Object calcularMediaAlturaHomens (float TotalAlturaHomens, int NumeroHomens) {
     if (NumeroHomens == 0) {
         return "Sem média!";
     }
     return TotalAlturaHomens / NumeroHomens;
 }


 public static void main(String []args){
     
    final Object resultado1 = calcularMediaAlturaHomens(1.84F, 2);
    final Object resultado2 = calcularMediaAlturaHomens(1.84F, 0);
    
    if( resultado1 instanceof Float) {
        float valor = (float)resultado1;
        System.out.println(valor);
    }
    

    if( resultado2 instanceof String ) {
        System.out.printf("É uma string: %s.\n", resultado2.toString());
    }  
 }

Correct, would you return a Exception (own preference) which is a mistake. Because, look at the context, you need men to calculate, if you don’t have men, you can’t calculate.

public static float calcularMediaAlturaHomens (float TotalAlturaHomens, int NumeroHomens) {
     if (NumeroHomens == 0) {
         throw new IllegalArgumentException("Sem média!");
     }
     return TotalAlturaHomens / NumeroHomens;
}


 public static void main(String []args){
    
    float a = calcularMediaAlturaHomens(1.31F, 12);
    System.out.printf("Média: %f.\n", a);
    
    float b = calcularMediaAlturaHomens(1.31F, 0); // o método irá lançar o erro, você faz o que precisa ser feito.
    
 }

However, another way, easier and less costly to Sisop, would be to return a negative number.

By the name of your parameters, you will never have a negative number(Positive / positive = positive). Then you can return -1 when numeroHomens == 0;

public static float calcularMediaAlturaHomens (float TotalAlturaHomens, int NumeroHomens) {
     if (NumeroHomens == 0) {
         return -1F;
     }
     return TotalAlturaHomens / NumeroHomens;
}

public static void main(String []args){

    float a = calcularMediaAlturaHomens(1.31F, 12);
    System.out.printf("Média: %f.\n", a);

    float b = calcularMediaAlturaHomens(1.31F, 0);
    if(b == -1F) { /** sem média */  }


 }
  • Could still return a Float instead of float and may be null, I consider it better to return a negative, although for this case it works. And could still use a Optional https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Optional.html. Creating a class just for this looks like a cannon to kill bird and return Object It really gets curious, it’s not a good idea. Almost not positive because this idea of "in Java everything is object" is wrong by several points of view.

0


The fact is if you’ve determined a kind of return that needs to be met, it’s a Java rule, at least as far as I know. may even be scammed as I will show but it is not interesting.

The scenario that I see most ideal would be you make this comparison in the execution of your application and or have a separate control method, some possible scenarios would be.

[EDITED] another possible scenario would declare a class and in turn work with the returns of attributes of that class, the code was added later.

public class Main {
    
    public static String calcularMediaAlturaHomens (float TotalAlturaHomens, int NumeroHomens) {
        if (NumeroHomens == 0) {
            return "Sem média!";
        }
        return ""+ TotalAlturaHomens / NumeroHomens;
    }
    static float media = 0F;
    public static void calcularMediaAlturaHomens2 (float TotalAlturaHomens, int NumeroHomens) {
         media = TotalAlturaHomens / NumeroHomens;
    }
    
    public static float calcularMediaAlturaHomen3 (float TotalAlturaHomens, int NumeroHomens) {
        return TotalAlturaHomens / NumeroHomens;
    }
// outra forma seria declarar ua classe para retorno
    public static MinhaClasseDeRetorno calcularMediaAlturaHomen4(float TotalAlturaHomens, int NumeroHomens) {
        MinhaClasseDeRetorno mcr = new MinhaClasseDeRetorno();
        if (NumeroHomens == 0) {
            mcr.message="Sem média!";
        }
        mcr.media = TotalAlturaHomens / NumeroHomens;
        return mcr;
    }
    
    public static void main(String[]args) {
        // caso um, retorne String mesmo
        System.out.println(calcularMediaAlturaHomens(200, 2));
        
        // retorne para uma variável de classe, poderia ser um atributo
        // ou metodo de retorno.
        calcularMediaAlturaHomens2(0, 2);
        System.out.println(media > 0 ? media : "Sem média!");
        
        // atribua o retorno em tempo de execução
        float media1 = calcularMediaAlturaHomen3(0, 2);
        System.out.println(media1 > 0 ? media1 : "Sem média!");

        // retorno a partir de uma classe, com comportamento em atributos
        System.out.println(calcularMediaAlturaHomen4(100,2));
        System.out.println(calcularMediaAlturaHomen4(0,2));
    }
}

class MinhaClasseDeRetorno {
    String message = "";
    float media = 0F;
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public float getMedia() {
        return media;
    }
    public void setMedia(float media) {
        this.media = media;
    }
    @Override
    public String toString() {
        return media > 0 ? ""+ media : message;
    }
}

in the above example I did three simple functions where one returns a string, another has no return and another returns the float, each with small features.

  • Couldn’t I create a Function without declaring its primitive type? So it would return the value in String or int according to the results.

  • @Daviribeiro. Java is not possible is a strongly typed language or the type of an object must be available(declared) at compile time otherwise the source is not compiled. The feature you are looking for is only present in weakly typed languages like Javascript.

Browser other questions tagged

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