package awb; import java.util.*; import java.net.*; import java.io.*; public class MadLibGenerator extends Object { private Vector quotes; private Random rand; private final static String SOURCE = "http://www.duke.edu/~srr1/cps1/misc/madlibs.dat"; public MadLibGenerator() { quotes = new Vector(); rand = new Random(); try { URL u = new URL(SOURCE); URLConnection uc = u.openConnection(); DataInputStream in = new DataInputStream(uc.getInputStream()); String line = in.readLine(); String current; while (line != null) { current = ""; while (! line.startsWith("%%%%%")) { current = current + line + "\n"; line = in.readLine(); } quotes.addElement(current); line = in.readLine(); } } catch (MalformedURLException ex) { System.out.println("Bad URL: " + SOURCE); quotes.addElement("No quotes available"); } catch (IOException ex) { System.out.println("Error getting stream from " + SOURCE); quotes.addElement("No quotes available"); } } public String getMadLib() { int next = rand.nextInt() % quotes.size(); if (next < 0) next *= -1; return (String)quotes.elementAt(next); } }