StockQuote.java


Below is the syntax highlighted version of StockQuote.java from §1.1 Programming Model.


/******************************************************************************
 *  Compilation:  javac StockQuote.java
 *  Execution:    java StockQuote xyz
 *  Dependencies: In.java
 *
 *  Print the stock price of the stock with the given symbol.
 *
 *  $ java StockQuote aapl
 *  Apple Computer Inc (AAPL)
 *  23.18
 *  Friday, February 27, 2004, 10:13am ET - U.S. Markets  close in 5 hours and 47 minutes.
 *
 *  % java StockQuote ibm
 *  International Business Machines Corp (IBM)
 *  97.07
 *  Friday, February 27, 2004, 10:13am ET - U.S. Markets  close in 5 hours and 47 minutes.
 *
 *  % java StockQuote msft
 *  Microsoft Corp (MSFT)
 *  26.51
 *  Friday, February 27, 2004, 10:13am ET - U.S. Markets  close in 5 hours and 47 minutes.
 *
 ******************************************************************************/

public class StockQuote {

    public static void main(String[] args) {
        String name = "http://finance.yahoo.com/q?s=" + args[0];
        In in = new In(name);
        String input = in.readAll();

        int p, from, to;

        // stock name
        p    = input.indexOf("Finance Search", 0);
        from = input.indexOf("<b>", p);
        to   = input.indexOf("</b>", from);
        String stock = input.substring(from + 3, to);
        StdOut.println(stock);


        // price
        p    = input.indexOf("Last Trade:", 0);
        from = input.indexOf("<b>", p);
        to   = input.indexOf("</b>", from);
        String price = input.substring(from + 3, to);
        StdOut.println(price);

        // date
        p    = input.indexOf("Help", 0);
        from = input.indexOf("<small>", p);
        to   = input.indexOf("</small>", from);
        String date = input.substring(from + 7, to);
        StdOut.println(date);

    }

}


Copyright © 2000–2019, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 07:59:46 EDT 2022.