我有一個String
陣列供乘客的國籍使用;查找字符串數組的平均值
String[] strNationality = new String[];
用戶可以輸入他們喜歡的任何國籍。但是我必須找到平均國籍。所以,例如,如果有五個人在公共汽車上;德語,德語,德語,法語,西班牙語。我可以看到德國人顯然是看平均水平,但是創建計算平均水平的方法最好的方法是什麼?
我有一個String
陣列供乘客的國籍使用;查找字符串數組的平均值
String[] strNationality = new String[];
用戶可以輸入他們喜歡的任何國籍。但是我必須找到平均國籍。所以,例如,如果有五個人在公共汽車上;德語,德語,德語,法語,西班牙語。我可以看到德國人顯然是看平均水平,但是創建計算平均水平的方法最好的方法是什麼?
我假設你的意圖平均意味着最重複的國家名稱。 您可以使用HashMap數據結構。
HashMap < String,Integer>:其中String是國家名稱,Integer將是計數。
一旦完成了所有輸入,您只需遍歷HashMap以查找最大值部分並打印相應的關鍵部分。
http://docs.oracle.com/javase/7/docs/api/java/util/Map.html
在你的情況下,它看起來像:
鍵 - > VALUE 德國 - > 3 法國 - > 1 西班牙 - > 1
迭代通過的值部分地圖將幫助您確定3是最大的一個,它的關鍵德國是您應該印刷的那個。
算法是這樣的:
非常感謝你!你是一個巨大的幫助 – Conor606
如果有國籍的人數不詳,我會用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);
}
}
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.
平均是一組數字,而不是字符串的函數。你需要首先爲字符串定義平均值 – gefei
我認爲你的意思是「模式」,這意味着在給定集合中國籍數最多。 –
術語「平均值」不適用於非數值。你probabyl意味着最高的國籍。 – AlexWien