首页 > 解决方案 > 即使我确定该项目在数组列表中,我的 binarySearch 也会返回负索引

问题描述

这就是我打印它的方式:

     else if (cmd.equalsIgnoreCase("I"))
     { 
        System.out.println("Enter item name to get price:");
        String n = in.nextLine();
        System.out.println( table.lookup_by_item(n) + "\n");
     }

这就是我存储信息和实现二进制搜索的方式:

public class LookupTable
{ 
private ArrayList<Item> Item_key; 
public LookupTable()
{

   Item_key = new ArrayList<Item>();      

}

public void read(Scanner in) {        

   String k = null, v = null;

  while(in.hasNextLine()) {
         k = in.nextLine();
         v = in.nextLine();
         Item_key.add(new Item(k,v));
         //System.out.println(k);
         //System.out.println(v);
     }
}   
public String lookup_by_item(String n)
{       
   Collections.sort(Item_key);     

   int index_found = Collections.binarySearch(Item_key, new Item(n, null));
   System.out.println(index_found);
   String itemn="";

   if(index_found >= 0) {

        itemn = Item_key.get(index_found).getValue();

}
return itemn;          

这是我的项目类:

public class Item implements Comparable<Item>
{
public String key;
public String value;

public Item(String k, String v)
{ 
  key = k;
  value = v;
}

public String getKey()
{ 
  return key;
}


public String getValue()
{ 
  return value;
}

public int compareTo(Item otherObject)
{
  Item other = (Item) otherObject;
  return key.compareTo(other.key);

这是我要进行二进制搜索的文本文件的内容:

Flat White
4.05
Cappuccino
4.45
Latte
4.45
Americano
3.35
Iced Coffee
3.25
Cold Brew
3.75

如果我运行它并搜索任何随机饮料,系统将打印出负数 index_found。我试图改变 return "key.compareTo(other.key);" 到“0”,但无论我输入什么,它都会一直返回“3.35”。“3.35”是项目“Americano, 3.35”的值。

任何聪明的编码器,请教我如何在输入密钥时获得我想要的值。就像当我输入“卡布奇诺”时,我可以得到 4.45 的回报。

标签: javabinary-search

解决方案


我编译并执行了上面的代码,它工作正常并给出了正确的答案。当您ie Item_key时,它唯一一次返回负索引值。我猜您犯了一些拼写/错字错误,因此它返回了负索引。enter some key value which is not there in your ArrayList


推荐阅读