-1
I have this method in the secondary class to calculate the median of a vector:
public class Funcoes {
....
public void setMediana(int[] valores) {
double med;
Arrays.sort(valores);
int meio = valores.length / 2;
if (valores.length % 2 == 0) {
int esquerda = valores[meio - 1];
int direita = valores[meio];
med = (double) (esquerda + direita) / 2;
} else {
med = (double) valores[meio];
}
this.mediana = med;
}
public double getMediana() {
return mediana;
}
And that’s my main class:
{
public class EstatisticaX3 {
public static void main(String[] args) {
int[] valores = {56, 61, 57, 77, 62, 75, 63, 55, 64, 60, 60, 57, 61, 57, 67, 62, 69, 67, 68, 59, 65,
72, 65, 61, 68, 73, 65, 62, 75, 80, 66, 61, 69, 76, 72, 57, 75, 68, 83, 64, 69, 64, 66, 74,
65, 76, 65, 58, 65, 64, 65, 60, 65, 80, 66, 80, 68, 55, 66, 71};
Funcoes exemplo01 = new Funcoes(valores);
System.out.println(exemplo01.getMedia());
System.out.println("");
System.out.println(exemplo01.setFrequenciaOrdem(valores));
System.out.println(" ");
System.out.println(exemplo01.getMediana()); */aqui que o resultado é 0.0*
}
}
I tried to use the variable med as integer and give Typecast, I tried changing the other variables as well, although I thought that this way above would be the correct one and still only gives 0.0
The problem is in
med = (double) (esquerda + direta)/2
, right? It happens because thecast
occurs in the division, not in the numerator. Divide by2.0
i cast in the numerator:med = ((double) esquerda+direita)/2
– Jefferson Quesado
Ok, I thought the mistake was in the calculation, but apparently it is in the life cycle of the variables. Why do you have a
set
that is not called? And why store the value of a derived attribute?– Jefferson Quesado
It’s true, I’m still learning how to use getters and setters, my mistake was in this same part. I deleted the get and used the direct set and it worked. Thanks anyway!
– Luis Fernando