Search code examples
javaarraysinputaverage

How can I sum and average my array in Java


I want to sum and average my array in Java. How can I do that?

public class EjerciciosArrays extends javax.swing.JFrame {
    
    ArrayList<Double> mi_arrayHtmlyCSS;
    ArrayList<Double> mi_arrayCplusplus;
    ArrayList<Double> mi_arrayJava;
    ArrayList<Double> mi_arrayPython;
    ArrayList<Double> mi_arrayJavaScript;
    ArrayList<Double> mi_arrayPhp;
    ArrayList<Double> mi_arrayMongoDB;
    ArrayList<Double> mi_arrayMysql;
    ArrayList<Double> mi_arrayAngularJS;
    ArrayList<Double> mi_arrayExpressJS;
    
    private void btnHtmlyCSSActionPerformed(java.awt.event.ActionEvent evt) { 
    
     mi_arrayHtmlyCSS  = new ArrayList<>(); //
          
            for (int i = 1; i <= 4; i++){
                mi_arrayHtmlyCSS.add(Double.parseDouble(JOptionPane.showInputDialog("Ingrese EVA "+(i)))); // 
                   }
           mi_arrayHtmlyCSS.forEach((a)-> {
            this.txtHtmlyCSS.append(a+"\n");
           });
           
        }   
    
        
            
           mi_arrayHtmlyCSS.forEach((a)-> {
            this.txtHtmlyCSS.append(a+"\n");
           });
           
        } 

Solution

  • I don't understand clearly what's you piece of code is for, but I'm gonna try to help you. If you want to calculate the sum of elements in ArrayList you could do it like that

    public double sum(List<Double> list) {
    
    
        double sum=0d;
        for(Double value:list) {
            sum+=value;
        }
        return sum;
    
    }
    

    In order to calculate the average you just have to divide the sum by the size of an array.

    double sum=sum(mi_arrayHtmlyCSS);
    double avg=sum/mi_arrayHtmlyCSS.size();
    

    I didn't check nullable and divide by zero for simplicity.