找到String Array的平均值

时间:2015-10-20 18:55:25

标签: java arrays average

我有一个String阵列,用于乘客的国籍;

String[] strNationality = new String[];

用户可以输入他们喜欢的任何国籍。但是我必须找到平均国籍。那么,例如,如果有五个人在公共汽车上的国籍;德语,德语,德语,法语,西班牙语。我可以看到德国人显然是看待它的平均值,但是创建计算平均值的方法的最佳方法是什么?

3 个答案:

答案 0 :(得分:4)

如果有不明国籍的国籍,我会使用Map将国籍存储为key,将计数存储为value。如果存在下一个国籍,则在Map对象中增加该国籍的值。如果没有,则创建新的并将其添加到Map对象。

Map<String, Integer> nationalityCount = new Map<String, Integer>();
for(int i = 0 ; i < strNationality.length(); i++) {
    String nationality = strNationality[i];
    if(nationalityCount.containsKey(nationality) {
        int newCount = nationalityCount.get(nationality) + 1; 
        nationalityCount.put(nationality, newCount);
    }
    else {
        nationalityCount.put(nationality, 1);
    }
}

答案 1 :(得分:0)

我假设你的意图平均意味着最重复的国家名称。 您可以使用HashMap数据结构。

的HashMap&LT; String,Integer&gt;:其中String是国家名称,Integer将是计数。

完成所有输入后,只需遍历HashMap即可找到最大值部分并打印相应的关键部分。

http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

在你的情况下,它看起来像:

KEY - &gt;值 德国 - &gt; 3 法语 - &gt; 1 西班牙语 - &gt; 1

迭代地图中的VALUE部分可以帮助您确定3是最大的一个,其关键德国是您应该打印的那个。

算法看起来像这样:

  1. 阅读country array中的每个条目。
  2. 如果当前国家/地区不在HashMap中,则将其添加到地图中,其中KEY为国家/地区名称,VALUE为1。
  3. 如果当前国家/地区存在于HashMap中,则将现有条目更新为VALUE为2.
  4. 重复上述步骤,直到完全读取数组。
  5. 遍历地图以找到最高的值。
  6. 获取最高VALUE的相应KEY 打印它。

答案 2 :(得分:0)

String[] strNationality = new String[]; //this array must be filled first.


string _MajorNationality = "";
int _RepeatedTimes = 0;
for(int i = 0; i < strNationality.length; i++){
    int currentRepeat = 0;
    for(int j = i; j < strNationality.length; j++){
        if(strNationality[i].equals(strNationality[j])){
            currentRepeat++;
        }
    }
    if(_RepeatedTimes < currentRepeat){
        _MajorNationality = strNationality[i];
        _RepeatedTimes = currentRepeat;
    }
}

//_MajorNationality would be the most repeated nationality.
//_RepeatedTimes would be how many times it repeated.