Result 0.0 - even with Typecast or changing variable types

Asked

Viewed 57 times

-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 the cast occurs in the division, not in the numerator. Divide by 2.0 i cast in the numerator: med = ((double) esquerda+direita)/2

  • 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?

  • 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!

1 answer

0


You’re not calling the method setMediana so the result is the initial value of the variable mediana, that is to say, 0.0.

Try something like

System.out.println(" ");
exemplo01.setMediana(valores);
System.out.println(exemplo01.getMediana());

(untested)

is a bit confused, I would make a single method calcularMediana instead of the setMediana and getMediana

  • I did it that way and it worked! Thanks!

  • @Luisfernando , the best way to thank is to mark this response as accepted

  • 1

    Opa blz, I’m learning to use the stack now!

Browser other questions tagged

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