CSCI A202 - Introduction to Programming (II)

Lecture 21: Set Implementation with Hashtables Terminal I/O

Here's the code we wrote in class today.

tucotuco.cs.indiana.edu% vi Hashes.java

tucotuco.cs.indiana.edu% ls -l Hashes.* -rw-r--r-- 1 dgerman students 1389 Apr 1 14:35 Hashes.java
tucotuco.cs.indiana.edu% cat Hashes.java
import java.io.*; import java.util.*; class Hashes { public static void main(String[] args) { Hashtable h = new Hashtable(); try { BufferedReader b = new BufferedReader( new InputStreamReader( System.in)); System.out.println("Ready for input."); while (true) { StringTokenizer s = new StringTokenizer(b.readLine()); String command = "<cmd>", argument = "<arg>"; if (s.hasMoreTokens()) { command = s.nextToken(); } if (s.hasMoreTokens()) { argument = s.nextToken(); } if ( command.equals("add")) { h.put(argument, argument); System.out.println("OK"); } else if (command.equals("delete")) { h.remove(argument); System.out.println("OK"); } else if (command.equals("list")) { Enumeration e = h.keys(); while (e.hasMoreElements()) { System.out.println(" :" + e.nextElement()); } } else if (command.equals("contains")) { System.out.println(h.containsKey(argument)); } else if (command.equals("quit")) { System.exit(0); } else { System.out.println("Unknown command: " + command + " " + argument); } } } catch (Exception e) { System.out.println("E: " + e.toString()); } } }
tucotuco.cs.indiana.edu% javac Hashes.java
What follows is a session with our program. Computer answers in blue.

tucotuco.cs.indiana.edu% java Hashes
Ready for input. list add one OK add two OK add three OK list :one :three :two contains three true delete two OK list :one :three contains two false destroy one Unknown command: destroy one Unknown command: <cmd> <arg> destroy Unknown command: destroy <arg> add OK list :one :three :<arg> remove <arg> Unknown command: remove <arg> delete <arg> OK list :one :three quit tucotuco.cs.indiana.edu%
I will go over this again on Tuesday, although in a slightly different way.