AshRo
AshRo

Reputation: 33

Reading input file with names and scores, use ArrayLists to compute values

I haven input file in the following format: Rory Williams 88 92 78 -1 James Barnes 87 76 91 54 66 -1 and so on....

I want to read the scores from each person until I hit -1 and store the scores in an ArrayList. I understand how to get the scores into an ArrayList for one person, but I don't understand how to group the scores by person or to read scores in for the next person.

For an individual, my method looks like this:

private static ArrayList<Integer> readNextSeries(Scanner in) {
        ArrayList<Integer> scores = new ArrayList<Integer>();
        int x=0;
        while (in.hasNextLine())
        {   
            if (scores.get(x)!=-1)
            {
            scores.add(in.nextInt());
            x++;
            }
        }
        return scores;
    }

We have to be able to somehow store the scores for different people because then we have to compute the mean, median, maximum, and minimum score for each person and then the highest average score and lowest average score out of the group of people. My only other thought was that maybe I could create a separate ArrayList for each person using their name as the ArrayList name - I'm not sure that's correct though.

Upvotes: 1

Views: 504

Answers (2)

ToYonos
ToYonos

Reputation: 16833

Your method should look like this for one individual

private static ArrayList<Integer> readNextSeries(Scanner in)
{
    ArrayList<Integer> scores = new ArrayList<Integer>();
    if (in.hasNextLine())
    {
        int score = in.nextInt();
        if (score !=-1)
        {
            scores.add(score);
        }
        else
        {
            return scores;
        }
    }
    return scores;
}

Because scores is at first an empty ArrayList and scores.get(x) with x = 0 will throw a IndexOutOfBoundsException

For all the file :

Map<String, List<Integer>> allScores = new HashMap<String, List<Integer>>();
while (in.hasNextLine())
{
     String name =...; // get the name with scanner
     allScores.put(name, readNextSeries(in);
}

Upvotes: 0

aarti
aarti

Reputation: 2865

You should use a HashMap. This is a perfect usecase for this data structure. To be able to group things and access them based on it's association. In some languages it is called an associative array or a dictionary

http://en.wikipedia.org/wiki/Hash_table

Upvotes: 1

Related Questions