2015-10-20 29 views
0

我有一个String阵列供乘客的国籍使用;查找字符串数组的平均值

String[] strNationality = new String[]; 

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

+0

平均是一组数字,而不是字符串的函数。你需要首先为字符串定义平均值 – gefei

+0

我认为你的意思是“模式”,这意味着在给定集合中国籍数最多。 –

+0

术语“平均值”不适用于非数值。你probabyl意味着最高的国籍。 – AlexWien

回答

0

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

HashMap < String,Integer>:其中String是国家名称,Integer将是计数。

一旦完成了所有输入,您只需遍历HashMap以查找最大值部分并打印相应的关键部分。

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

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

键 - > VALUE 德国 - > 3 法国 - > 1 西班牙 - > 1

迭代通过的值部分地图将帮助您确定3是最大的一个,它的关键德国是您应该印刷的那个。

算法是这样的:

  1. 阅读来自全国阵列中的每个条目。
  2. 如果当前国家/地区不在HashMap中,则将其添加到KEY作为国家名称和VALUE为1的地图。
  3. 如果当前国家存在于HashMap中,则将VALUE的现有条目更新为2。
  4. 重复上述步骤直到完全读取数组。
  5. 迭代通过地图查找最高值。
  6. 获取最高价值的相应KEY并打印 。
+0

非常感谢你!你是一个巨大的帮助 – Conor606

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); 
    } 
} 
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.