Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList has two elements, is it possible to find an average of the int element?

This small project consists of two classes and one ArrayList. The ArrayList has two elements: a name and a score. Is it possible to find the average of the element score?

Class classroom:

/**
 * This class creates the names and scores of the students
 */
public class Classroom
{
public int score;
public String name;

/**
 * Constructor for the Class that adds a name and a score.
 */
public Classroom(String aName, int aScore)
{
    score = aScore;
    name = aName;
}

/**
 * Return the name of the students
 */
public String returnName()
{
    return name;
}

/**
 * Return the scores
 */
public int returnScore()
{
    return score;
}
}

Class TestScores:

import java.util.ArrayList;
/**
 * Print test scrose and student names as well as he average for the class.
 */
public class TestScores
{
private ArrayList<Classroom> scores;
public int studentScores;

/**
 * Create a new ArrayList of scores and add some scores
 */
public TestScores()
{
    scores = new ArrayList<Classroom>();
}

/**
 * Add a new student and a new score.
 */
public void add (String name, int score)
{
    scores.add(new Classroom(name, score));
        if(score > 100){
            System.out.println("The score cannot be more than 100");
        }

}

Wouldn't you be able to use a for each loop, create a local variable to store the student score from the returnScore method in the classroom class and divide it by the array size?

like image 564
feelingstoned Avatar asked Dec 03 '25 13:12

feelingstoned


1 Answers

Using Java 8 streams, this should do the work

public double getAvg(){
    return scores.stream()
                 .mapToInt(x -> x.returnScore())
                 .average()
                 .getAsDouble();
}
like image 92
Yassin Hajaj Avatar answered Dec 05 '25 04:12

Yassin Hajaj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!