我有一個 HashMap 定義為:Map<String, Double> data = new HashMap<String, Double>();我正在嘗試打印出具有最高 Double 值的 5 個字符串。我嘗試通過對每個循環(huán)運(yùn)行 5 次并保存最高值來做到這一點(diǎn),同時我將整個 HashMap 迭代 5 次,但在 if 語句中出現(xiàn)空指針異常錯誤。int highest = 0;String highestkey; for(int i=0; i<5; i++){ for(Map.Entry<String, Double> x : data.entrySet()){ if(data.get(x) > highest){ highestkey = x.getKey(); } } System.out.println(highestkey); info_words.remove(highestkey); }我的代碼應(yīng)該做的是在解析 HashMap 時跟蹤最高的 Double 值,然后最終打印最高的鍵,然后將其刪除,因此沒有重復(fù),然后再重復(fù)該過程 4 次,但它不能作為故意的
1 回答

Helenr
TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超4個贊
嘗試這個:
Double highest = 0.0;
String highestkey = "";
for (int i = 0; i < 5; i++) {
for (Map.Entry<String, Double> x : data.entrySet()) {
if (x.getValue() > highest) {
highest = x.getValue();
highestkey = x.getKey();
}
}
System.out.println(highestkey);
//remove highest here
}
添加回答
舉報(bào)
0/150
提交
取消