Java 我如何编写方法来查找项目的价格并返回它?项目数组中的项目索引与价格数组中的索引相对应

Java 我如何编写方法来查找项目的价格并返回它?项目数组中的项目索引与价格数组中的索引相对应,java,arraylist,Java,Arraylist,你应该用地图来做这件事。例如,如果要使用Map,只需使用Map.get(input)即可获得双倍的价格。您只需使用重复的Map.put(String,Double)调用初始化Map。这可以通过静态初始化完成,如: public class OnlineCTStores { //avaliable store items public static String[] ITEMS = {"Cactus", "T Shirt", "air", "Terracotta Necklace"

你应该用地图来做这件事。例如,如果要使用
Map
,只需使用
Map.get(input)
即可获得双倍的价格。您只需使用重复的
Map.put(String,Double)
调用初始化
Map
。这可以通过静态初始化完成,如:

public class OnlineCTStores {
    //avaliable store items
    public static String[] ITEMS = {"Cactus", "T Shirt", "air", "Terracotta Necklace", "Coffee Mug", "Wood Crate Wall Storage", "Blanket", "Knife", "Copper Coffee and Tea Kettle", "Wall Art", 
            "Marble Clock", "Natural Bench", "Llama Valley Framed Print", "Gold Metal Frame Mirror", "Fork", "Star Wars game", "Barracuda", "Anchor", "Sunlight", "planet Saturn"}; 
    //corresponding prices
    public static double[] PRICES = {49.99, 13.99, 5.99, 14.99, 29.99, 11.50, 79.99, 23.80, 27.99, 39.44, 78.40, 299.30, 55.00, 176.89, 4.99, 67.00, 8.19, 50.00, 1500, 400};

    public double findItemPrice(String item){
        //TODO

        return 0.0;
    }
}

为了获得更好的时间复杂度,您可以对项目数组进行排序并调用二进制搜索函数。排序是O(nlogn),搜索是O(logn)

更新

sort()将修改现有数组。如果要使其保持不变,可能需要将其复制到新阵列:

public double findItemPrice(String item){
   Arrays.sort(ITEMS);
   int matchIndex = Arrays.binarySearch(ITEMS, item);
   if (matchIndex == -1) throw new RuntimeException("Item price  not found, " + 
   input);
   return PRICES[matchIndex];
}

你自己没试过?如果不是,为什么不呢?使用
映射
如果要返回索引,那么返回整数不是更好吗?而不是双精度。@Aominè我想他想用这个方法返回一个价格。
intplace=Arrays.asList(ITEMS.indexOf(item)
退货价格[地点]
public static double findItemPrice(String input) {
    int matchIndex = -1;
    for (int i = 0; i < ITEMS.length; i++)
        if (input.equals(ITEMS[i])) {
            matchIndex = i;
            break;
        }

    if (matchIndex == -1) throw new RuntimeException("String not found, " + input);
    return PRICES[matchIndex];
}
public double findItemPrice(String item){
   Arrays.sort(ITEMS);
   int matchIndex = Arrays.binarySearch(ITEMS, item);
   if (matchIndex == -1) throw new RuntimeException("Item price  not found, " + 
   input);
   return PRICES[matchIndex];
}
int[] copy = Arrays.copyOf(ITEMS, ITEMS.length);