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 */ }
}
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().– Augusto Vasques
@Augustovasques is easier to return -1 in his case.
– sgtcortez