发布
社区首页 >问答首页 >读取带有名称和分数的输入文件,使用ArrayLists计算值

读取带有名称和分数的输入文件,使用ArrayLists计算值
EN

Stack Overflow用户
提问于 2014-11-14 08:36:49
回答 2查看 415关注 0票数 1

我还没有输入以下格式的文件: Rory Williams 88 92 78 -1 James Barnes 87 76 91 54 66 -1,依此类推...

我想读取每个人的分数,直到我点击-1,并将分数存储在ArrayList中。我知道如何将分数放入一个人的ArrayList中,但我不知道如何按人对分数进行分组,或者为下一个人读入分数。

对于个人而言,我的方法如下所示:

代码语言:javascript
代码运行次数:0
复制
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名称-但我不确定这是否正确。

EN

回答 2

Stack Overflow用户

发布于 2014-11-14 08:42:10

您应该使用HashMap。对于这种数据结构,这是一个完美的用例。能够对事物进行分组,并根据其关联来访问它们。在某些语言中,它被称为associative arraydictionary

http://en.wikipedia.org/wiki/Hash_table

票数 1
EN

Stack Overflow用户

发布于 2014-11-14 08:48:16

对于一个人来说,你的方法应该是这样的

代码语言:javascript
代码运行次数:0
复制
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 = 0scores.get(x)将抛出一个IndexOutOfBoundsException

对于所有文件:

代码语言:javascript
代码运行次数:0
复制
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);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26921081

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档