Search code examples
javacalculatormode

Statistical mode (Calculator Java)


Well, I'm programming an arithmetic calculator using Java, and I've tried to implement a function that calculates the mode. The problem is that for some reason it's not working right. Here's the function:

public static String moda(Double[] valores){

    Double resultado = null;
    Integer contador = 0;
    Integer contadorFinal = 0;

    for(int i = 0; i < valores.length; i++){

        contador = 0;
        for(int j = 0; j < valores.length; j++){

            if(valores[i] == valores[j]) contador++;
        }

        if(contador > contadorFinal){
            resultado = valores[i];
            contadorFinal = contador;
        }
    }

    return "La moda es " + resultado + " que se repite un total de " + contadorFinal + " veces.";
}

For some reason, it's always returning me the first value of the array (for example, if Double[] valores contains (4,7,7,8,8,8) it will return me 4); and the mode is always 1 as well.

I've been looking the code again and again, and for me it looks fine. Can you help me, please?


Solution

  • It's because you are comparing Double, a class, by equality. Use double or use Double.compare().

    for(int i = 0; i < valores.length; i++){
    
        contador = 0;
        for(int j = 0; j < valores.length; j++){
    
            if( Double.compare( valores[i], valores[j] ) == 0 ) 
               contador++;
        }
    
        if(contador > contadorFinal){
            resultado = valores[i];
            contadorFinal = contador;
        }
    }