简体   繁体   English

如何为以下情况声明2d数组?

[英]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. 玩家#1击球3次并得分0、1、4。玩家#2击球5次并得分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). Java中的多维数组只是一个数组,其中每个元素也是一个数组(依此类推)。 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 以下使用Collection的方法更加灵活

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. 等等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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