简体   繁体   中英

How to declare a 2d array for following scenario?

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.

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];
    }

Do you have to use arrays? The below approach using Collection s 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM