Hi!
I'm working on a school project and ran into a problem.
We're creating an ArrayList of basketball games where each game is set up as:

public Game (String homeTeam, int htScore, String opponent, int oppScore)
    {
        this.homeTeam = homeTeam;
        this.htScore = htScore;
        this.opponent = opponent;
        this.oppScore = oppScore;
    }

One of the tasks is to find the average of the Home team scores.
I don't understand how to go through and just select that element from the index.

Right now I have:

int homesum = 0;
        for (int i = 0; i < this.size(); i++)
        {
         homesum = homesum + Integer.parseInt(theDB.get(i).htScore);
        }

but I realize that won't work.

Any help would be appreciated.
Thanks!

actually, that is half the work.
allthough it's better to write it a bit like:

... Integer.parseInt(((Game)theDB.get(i)).getHTScore());

allowing your instance variables to be public accessible is a bit risky, using mutotars (setter-s / getter(s)) is a better approach.

next to that, you'll need to keep a counter, that counts the number of scores, and that divide the homesum value with the value of that counter after the last iteration.

1. Declare and initialise your ArrayList as as ArrayList of Games to avoid casting and possible errors ArrayList<Game> theDB = new ArrayList<Game>(); 2. htScore is already an int, so there's no need to use Integer.parseInt - that's just for where the data is in a String. homesum += theDB.get(i).getHtScore(); where getHtScore() is a public accessor method that returns the value of htScore.

3. No need to keep a counter, you can use theDB.size()

Thank you both very much!
With your help, I came up with:

int homesum = 0;
        for (int i = 0; i < theDB.size(); i++)
        {
         homesum += theDB.get(i).getHtScore();
         }
        int homeaverage = homesum/theDB.size();
            
        System.out.println("Mean Home Team score: " + homeaverage);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.