import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.MalformedURLException; import java.util.StringTokenizer; import java.util.Scanner; /** Here is a simple Web robot that allows the user to lookup a share price. * Let's assume the stock symbol is given as a command-line argument. */ public class Driver { public static void main(String [] args) throws MalformedURLException, IOException, InterruptedException { if (args.length == 0) { System.out.printf("Usage: java Driver \n"); System.exit(1); } String symbol = args[0]; String urlString = "http://finance.yahoo.com/q?s=" + symbol; URL url = new URL (urlString); InputStream urlIn = url.openStream(); Scanner in = new Scanner(urlIn); String line = ""; // Look for the line from the Web page that says "Last Trade:" boolean foundData = false; while(in.hasNextLine()) { line = in.nextLine(); if (line.indexOf("Last Trade:") >= 0) { foundData = true; break; } } // If we've gone thru the whole Web page and found no trade data, exit. if (! foundData) { System.out.printf("I couldn't find %s's trade data, sorry.", symbol); System.exit(1); } // Okay, it's a very long line, but shortly after the string "Last Trade" // we should see the share price, as in this example: // 8%">Last Trade: // 107.99< int position = line.indexOf("Last Trade:"); line = line.substring(position, position + 100); // Now that we have an extract of the Web page containing the desired // price: // Set up a StringTokenizer to token out the '<' and '>' symbols, and // look for the token that has a '.' in it. StringTokenizer tok = new StringTokenizer(line, "<>"); while(tok.hasMoreTokens()) { String token = tok.nextToken(); if(token.contains(".")) { double latestPrice = Double.parseDouble(token); System.out.printf("The latest share price is $ %.2f\n", latestPrice); break; } } } }