/* Example of a Web robot. Let's write a program that will go to the Web * and read a share price. * We can generalize the program, so it's not always just IBM. */ import java.io.*; import java.net.*; import java.util.*; public class Driver2 { public static void main(String [] args) throws MalformedURLException, IOException, InterruptedException { // The following code reads from the command line. // The user will enter only the stock symbol at the command line, // and we'll just buy 200 shares of it. /* Stock company = new Stock(args[0]); // Time to buy ... hold ... and sell stock! double cost = company.buy(200); Thread.sleep(15 * 1000); double proceeds = company.sell(200); System.out.println(company); */ // Read our desired portfolio from portfolio.txt // Feel free to change the desired portfolio before running the program! // But please keep it short (~4 stocks). // Each line of portfolio.txt has a stock symbol and number of shares. double totalInvested = 0.00; double totalProceeds = 0.00; ArrayList list = new ArrayList(); BufferedReader inFile = new BufferedReader(new FileReader("portfolio.txt")); // Read portfolio.txt and "buy" the stocks. while(true) { String line = inFile.readLine(); if (line == null) break; StringTokenizer tok = new StringTokenizer(line, " \t"); String stockSymbol = tok.nextToken(); int numShares = Integer.parseInt(tok.nextToken()); Stock company = new Stock(stockSymbol); totalInvested += company.buy(numShares); list.add(company); } // Hold ... wait time. Thread.sleep(30 * 1000); // Sell stocks! for (int i = 0; i < list.size(); ++i) { totalProceeds += list.get(i).sellAll(); } // How did we do? for (int i = 0; i < list.size(); ++i) { System.out.println(list.get(i)); } System.out.printf("total cost $ %.2f, total proceeds $ %.2f\n", totalInvested, totalProceeds); double profit = totalProceeds - totalInvested; double percentProfit = 100.0 * (profit / totalInvested); if (percentProfit > 0.0) { System.out.printf("PROFIT = $%.2f or %.1f%% of your investment.\n", profit, percentProfit); } else if (percentProfit < 0.0) { System.out.printf("LOSS = $%.2f or %.1f%% of your investment.\n", -profit, percentProfit); } else { System.out.printf("You broke even on your $%.2f investment.\n", totalInvested); } } }