2015-10-20 87 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.