Skip to content

Instantly share code, notes, and snippets.

@RupW
Created November 26, 2019 16:32
Show Gist options
  • Save RupW/7c1f83ba9df4f38f04a303de431cb3e4 to your computer and use it in GitHub Desktop.
Save RupW/7c1f83ba9df4f38f04a303de431cb3e4 to your computer and use it in GitHub Desktop.
// https://stackoverflow.com/q/59054704/243245
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class BinarySearchExample {
public static void main( String[] args )
throws IOException
{
LookupTable table = new LookupTable();
table.read(new Scanner(new File("input.txt")));
Scanner in = new Scanner(System.in);
System.out.println("Enter item name to get price:");
String n = in.nextLine();
System.out.println( table.lookup_by_item(n) + "\n");
}
}
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;
}
}
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment