[英]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.