【发布时间】:2020-02-16 10:22:21
【问题描述】:
基本上,我想使用用户给定的值遍历哈希图,但还包括任何具有键的较小值“价格”。具有键的可能值是 1250、900、600、300。
例如如果用户输入 600 但有 300 值的键,则打印 600 和 300 值的所有键。
这是我目前所拥有的,但它只会打印初始值的键,而不是较低的键。
private Map<Integer, Integer> prices = new HashMap<>();
private Map<Integer, Integer> bestPrices = new HashMap<>();
public void findBestPrice(LithiumPricing obj, Integer value)
{
//get hashmap prices from class LithiumPricing.
prices = obj.getPrices();
bestPrices.clear();
if (prices.containsValue(value)){
for (Map.Entry<Integer, Integer> entry : prices.entrySet()) {
if (entry.getValue() <= value){
bestPrices.put(entry.getKey(), value);
}
}
}
}
【问题讨论】:
-
“打印”是什么意思?那里没有打印任何东西
-
您的代码看起来不错。当您尝试使用值 (1250,900,600,300) 和 600 作为输入时,bestPrices 地图将只包含 600 而不是 300?