我还没有输入以下格式的文件: Rory Williams 88 92 78 -1 James Barnes 87 76 91 54 66 -1,依此类推...
我想读取每个人的分数,直到我点击-1,并将分数存储在ArrayList中。我知道如何将分数放入一个人的ArrayList中,但我不知道如何按人对分数进行分组,或者为下一个人读入分数。
对于个人而言,我的方法如下所示:
private static ArrayList<Integer> readNextSeries(Scanner in) {
ArrayList<Integer> scores = new ArrayList<Integer>();
int x=0;
while (in.hasNextLine())
{
if (scores.get(x)!=-1)
{
scores.add(in.nextInt());
x++;
}
}
return scores;
}
我们必须能够以某种方式存储不同人的分数,因为然后我们必须计算每个人的平均值、中位数、最高和最低分数,然后计算一组人中的最高平均分数和最低平均分数。我唯一的另一个想法是,也许我可以为每个人创建一个单独的ArrayList,使用他们的名字作为ArrayList名称-但我不确定这是否正确。
发布于 2014-11-14 08:42:10
您应该使用HashMap
。对于这种数据结构,这是一个完美的用例。能够对事物进行分组,并根据其关联来访问它们。在某些语言中,它被称为associative array
或dictionary
发布于 2014-11-14 08:48:16
对于一个人来说,你的方法应该是这样的
private static ArrayList<Integer> readNextSeries(Scanner in)
{
ArrayList<Integer> scores = new ArrayList<Integer>();
if (in.hasNextLine())
{
int score = in.nextInt();
if (score !=-1)
{
scores.add(score);
}
else
{
return scores;
}
}
return scores;
}
因为scores
最初是一个空的ArrayList,而使用x = 0
的scores.get(x)
将抛出一个IndexOutOfBoundsException
对于所有文件:
Map<String, List<Integer>> allScores = new HashMap<String, List<Integer>>();
while (in.hasNextLine())
{
String name =...; // get the name with scanner
allScores.put(name, readNextSeries(in);
}
https://stackoverflow.com/questions/26921081
复制相似问题