我正在尝试创建一个类来表示水果店,并希望输出按价格排序的可用水果,从最便宜到最贵。但是,即使我按照最便宜到最贵的顺序将价格添加到我的 FruitPricesMap 中,它总是以相同的任意顺序打印水果?我怎样才能让它不这样做?
****水果商店.java****
import java.util.*;
public class FruitStore {
private Map<String, Double> fruitPricesMap;
public FruitStore() {
fruitPricesMap = new HashMap<>();
}
public boolean addOrUpdateFruit(String fruitName, double fruitPrice) {
fruitPricesMap.put(fruitName, fruitPrice);
return true;
}
public void printAvaliableFruit() {
System.out.println("Avaliable Fruit:");
for (String key : fruitPricesMap.keySet()) {
System.out.printf("%-15s %.2f", key, fruitPricesMap.get(key));
System.out.println();
}
}
}
****FruitStoreApp.java****
public class FruitStoreApp {
public static void main(String[] args) {
FruitStore fs = new FruitStore();
fs.addOrUpdateFruit("Banana", 1.00);
fs.addOrUpdateFruit("Apple", 2.00);
fs.addOrUpdateFruit("Cherries", 3.00);
fs.printAvaliableFruit();
}
}
****电流输出****
Avaliable Fruit:
Apple 2.00
Cherries 3.00
Banana 1.00
****期望的输出(从最便宜到最贵):****
Avaliable Fruit:
Banana 1.00
Apple 2.00
Cherries 3.00
守着星空守着你
犯罪嫌疑人X
相关分类