[英]I am trying to declare an 2d array with initialized column values but the following code gives "not a statement error"
[英]How to declare a 2d array for following scenario?
我的程序要求输入玩家人数并将输入捕获为整数。 现在,对于每个玩家,系统都会询问用户击打多少次。 用户可以输入任何整数。 而且,对于每只蝙蝠,我都需要记录得分情况,以便以后可以计算击球平均数和击打平均数。
现在,我需要将其存储在二维数组中。 玩家#1击球3次并得分0、1、4。玩家#2击球5次并得分1、1、0、3、4。
{0, 1, 4}
{1, 1, 0, 3, 4}
我正在努力创建这样的数组。
Java中的多维数组只是一个数组,其中每个元素也是一个数组(依此类推)。 这些数组中的每个数组可以具有不同的长度:
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];
}
您必须使用数组吗? 以下使用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));
如果要将分数添加到玩家的现有分数列表中:
scoreCard.put(playerId, scoreCard.get(playerId).add(newScore));
如果要计算给定玩家的击球平均值,请执行以下操作:
List<Integer> scores = scoreCard.get(playerId);
scores.stream().reduce(0, Integer::sum)/scores.size();
等等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.