import java.util.Scanner; import java.util.Hashtable; import java.util.Enumeration; import java.util.StringTokenizer; import java.io.FileInputStream; import java.io.FileNotFoundException; /** Example of using a Java hash table (with 'keys' and 'values') * In this example, we have different foods and what kinds (groups) they are. * The hash table functions we will practice are: * put, get, containsKey, containsValue, keys, toString * Note: a HashMap would do pretty much the same thing as a Hashtable. * * Basically, we now have an array-type data structure that can be * indexed by anything, such as by string. */ public class Driver { public static void main(String [] args) throws FileNotFoundException { Scanner in = new Scanner(new FileInputStream("food.txt")); Scanner kbd = new Scanner(System.in); Hashtable table = new Hashtable(); while(in.hasNextLine()) { String line = in.nextLine(); // On each line of input, we have a key and a value such as // banana = fruit --> banana is the key & fruit is the value // We want to tell Java that banana is a kind of fruit.... StringTokenizer tok = new StringTokenizer(line, "="); String key = tok.nextToken().trim(); String value = tok.nextToken().trim(); table.put(key, value); } // Now, we can print out the hashtable. It has its own toString(), // and notice that the order is not the same as we read in. System.out.printf("\n%s\n", table); // Look up keys in the hash table. System.out.printf("\nEnter a food, and I'll tell you what kind it is: "); String choice = kbd.nextLine(); if (! table.containsKey(choice)) System.out.printf("Sorry, I don't have %s on the menu.\n", choice); else System.out.printf("%s is a %s.\n", choice, table.get(choice)); // Look up values in the hash table. System.out.printf("\nWhat type of food do you want? "); choice = kbd.nextLine(); if (table.containsValue(choice)) { System.out.printf("Yes, I do have some %s.\n", choice); // Find all the foods that belong to that food group. // For some strange reason, keys() returns an Enumeration. Enumeration foods = table.keys(); while(foods.hasMoreElements()) { String food = foods.nextElement(); if (table.get(food).equals(choice)) System.out.printf("\t%s\n", food); } } else System.out.printf("Sorry, I don't have any %s.\n", choice); } }