0

My programs asks for number of players and captures the input as integer number. Now for each player the system asks the user, how many times to bat. User can enter any integer. And for each bat I need to capture runs scored so that I can later calculate batting average and slugging average.

Now I needed to store this in a 2d array. Player #1 bats 3 times and scores 0, 1, 4. Player #2 bats 5 times and scores 1, 1, 0, 3, 4.

{0, 1, 4}
{1, 1, 0, 3, 4}

I'm struggling on how to create such an array.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
flowgician
  • 63
  • 1
  • 1
  • 7

2 Answers2

1

A multidimensional array in java is just an array, where each element is also an array (and so on). Each of those arrays can be of a different length:

    int numPlayers = // get number of players.
    int[][] stuff = new int[numPlayers][];
    for(int i = 0; i < numPlayers; i++)
    {
        int numAtBats = // get number of at bats for this player.
        stuff[i] = new int[numAtBats];
    }
  • Thanks a lot. I didn't knew I can just work with one array at a time inside an array. This is really helpful – flowgician May 08 '15 at 23:38
1

Do you have to use arrays? The below approach using Collections is more flexible

HashMap<Integer, List<Integer>> scoreCard = new HashMap<>();

scoreCard.put(1, Arrays.asList(0,1,4));
scoreCard.put(2, Arrays.asList(1,1,0,3,4));

If you want to add a score to an already existing score list for a player:

scoreCard.put(playerId, scoreCard.get(playerId).add(newScore));

If you want to calculate batting average of a given player:

List<Integer> scores = scoreCard.get(playerId);
scores.stream().reduce(0, Integer::sum)/scores.size();

etc.

kaykay
  • 556
  • 2
  • 7