/************************************************************************* * This class find current stock info from Yahoo * It uses the In Class to read from a Url * @Author: http://www.cs.princeton.edu/introcs/31datatype */ public class StockQuote { String symbol; // Given symbol, get current stock price. /** * To create an object you must specify the symbol ->IE StockQuote("ibm") */ public StockQuote(String symbol){ this.symbol=symbol; } public double getPrice() { In page = new In("http://finance.yahoo.com/q?s=" + symbol); String input = page.readAll(); int trade = input.indexOf("Last Trade:", 0); // "Last trade:" index int from = input.indexOf("", from + 4); // ">" index int to = input.indexOf("", from); // "" index String price = input.substring(from + 1, to); return Double.parseDouble(price); } // Given symbol, get current stock price. public String getName() { In page = new In("http://finance.yahoo.com/q?s=" + symbol); String input = page.readAll(); int p = input.indexOf("", 0); int from = input.indexOf("Summary for ", p); int to = input.indexOf("- Yahoo! Finance", from); String name = input.substring(from + 12, to - 5); return name; } // Given symbol, get current stock price. public String getDate(String symbol) { In page = new In("http://finance.yahoo.com/q?s=" + symbol); String input = page.readAll(); int p = input.indexOf("<span id=\"yfs_market_time\">", 0); int from = input.indexOf(">", p); int to = input.indexOf("-", from); // no closing small tag String date = input.substring(from + 1, to); return date; } }