如何從散列圖中減去兩個值後返回最小差異的鍵?從散列表中減去兩個值後返回最小差異的關鍵?
例
first loop -> 10 - 8 = 2;
second loop -> 10 - 9 = 1;
third loop -> 10 - 7 = 3;
therefore second loop -> 10 - 9 = 1 is the smallest, so the key is "Three".
代碼
import java.util.HashMap;
public class Difference {
HashMap<String,Double> hashMap = new HashMap<>();
double firstValue = 0;
double secondValue = 0;
double difference = 0;
public Difference() {
hashMap.put("One", 10.0);
hashMap.put("Two", 8.0);
hashMap.put("Three", 9.0);
hashMap.put("Four", 7.0);
firstValue = hashMap.get("One");
for (String key : hashMap.keySet()) {
if(!key.equals("One")) {
secondValue = hashMap.get(key);
difference = Math.abs(secondValue - firstValue);
}
}
}
public static void main(String[] args) {
new Difference();
}
}
請幫助。謝謝。
你的問題可能是因爲你不喜歡你應該比較字符串。使用'key.equals(「One」);'而不是'=='。讓我知道如果這有助於我可以關閉你的問題。 – Maroun
另外請注意,您沒有將「差異」與先前的結果進行比較,因此最終結果將是最後一次迭代中的最後一次差異。 – Maroun
@MarounMaroun我知道。這就是爲什麼我要問如何從迭代中獲得最小的差異,並且我改變了!= to!key.equals(「One」) –