0

I have an object, with this attributes:

public class Club {

    private String name;
    private ArrayList<Integer> points;
    private int average;

    Club(String name, ArrayList<Integer> points, int average){
        this.name = name;
        this.points = new ArrayList<>();
        this.average = average;

I try to fill the arraylist with points with data from a txt file:

        while((currentLine = br.readLine()) != null){

            String name;
            ArrayList<Integer> points = new ArrayList<>();
            int average;
            String[] clubData = currentLine.split(",");
            name = clubData[0];

            int score2 = Integer.parseInt(clubData[2]);
            int score3 = Integer.parseInt(clubData[3]);
            int score4 = Integer.parseInt(clubData[4]);
            int score5 = Integer.parseInt(clubData[5]);

            points.add(score2);
            points.add(score3);
            points.add(score4);
            points.add(score5);

            average = points.stream().mapToInt(Integer::intValue).sum()/4;
            Club club = new Club(name, points, average);

When I print the objects, I get this:

Name: Clubname Points: [] Average: 6

So, the values of the file are saved in the list. Because the average (6) is calculated, and this is the good value. But, the list 'points' of the object itself is empty. Can anyone explain me this?

0

2 Answers 2

1

Your constructor in the Club class is making a new ArrayList every time. Change it to this

Club(String name, ArrayList<Integer> points, int average){
    this.name = name;
    this.points = points;
    this.average = average;
Sign up to request clarification or add additional context in comments.

2 Comments

Or if Club should be immutable, copy the values of the passed list using addAll.
Thanks! I'm not very experienced with Java as you can see. Keep on learning, thanks :)
1

Your constructor is ignoring points.

Either copy the list (shallow copy):

this.points = new ArrayList<>(points);

or keep the reference to the existing list:

this.points = points;

Additionally, you currently are using Java's integer division to calculate the average. Here it looks like it worked out because you aren't complaining that the average is incorrect, but in general you would want to keep your average as a double and divide by a double literal, 4.0:

average = points.stream().mapToInt(Integer::intValue).sum()/4.0;

Also, an IntStream provides an average calculation for you. The average method returns an OptionalDouble:

average = points.stream().mapToInt(Integer::intValue).average().getAsDouble();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.