Block.java /** A quantity and price of a block of stocks. */ public class Block
ID: 3859589 • Letter: B
Question
Block.java
/**
A quantity and price of a block of stocks.
*/
public class Block
{
private final int price;
private int quantity;
/**
Constructor.
@param quantity the quantity of this block.
@param price the price of this block.
*/
public Block(int quantity, int price)
{
this.price = price;
this.quantity = quantity;
}
public int getQuantity() { return quantity; }
public int getPrice() { return price; }
public void sell(int shares) { quantity -= shares; }
}
SimulationRunner.java
import java.util.Scanner;
/**
Runs a Stock Trading Simulation
*/
public class SimulationRunner
{
public static void main(String[] args)
{
StockSimulator sim = new StockSimulator();
Scanner in = new Scanner(System.in);
boolean done = false;
System.out.println("Stock Simulator Menu");
System.out.println("-----------------------------------------------");
System.out.println(" > buy stock-symbol quantity price");
System.out.println(" > sell stock-symbol quantity price");
System.out.println(" > quit to quit simulation.");
System.out.println();
while (!done)
{
System.out.print(" > ");
String action = in.next();
if (action.equals("buy"))
{
String symbol = in.next();
int quantity = in.nextInt();
int price = in.nextInt();
sim.buy(symbol, quantity, price);
}
else if (action.equals("sell"))
{
String symbol = in.next();
int quantity = in.nextInt();
int price = in.nextInt();
sim.sell(symbol, quantity, price);
}
else if (action.equals("quit"))
{
done = true;
}
}
}
}
StockSimulator.java
import java.util.LinkedList;
import java.util.Queue;
import java.util.Map;
import java.util.TreeMap;
/**
Class for simulating trading a single stock at varying prices.
*/
public class StockSimulator
{
private Map<String, Queue<Block>> blocks;
/**
Constructor.
*/
public StockSimulator()
{
. . .
}
/**
Handle a user buying a given quantity of stock at a given price.
@param quantity how many to buy.
@param price the price to buy.
*/
public void buy(String symbol, int quantity, int price)
{
. . .
}
/**
Handle a user selling a given quantity of stock at a given price.
@param symbol the stock to sell
@param quantity how many to sell.
@param price the price to sell.
*/
public void sell(String symbol, int quantity, int price)
{
. . .
}
}
INPUT SCRIPT
test.in
buy ATT 100 10
buy APPL 10 50
sell ATT 50 13
buy ATT 100 15
sell APPL 5 55
buy GOOG 100 6
sell APPL 5 56
sell ATT 120 18
sell ATT 30 20
buy APPL 10 50
sell GOOG 80 8
sell GOOG 20 5
sell APPL 10 53
quit
Explanation / Answer
Capital gains yield=Stock price at the end of year-Stock price at beginning of year/Stock price at beginning of year
=(41-37)/37
=10.81%
Dividend yield=Dividend next yearInitial stock price
=0.28/37
=0.76%
Total rate=(10.81+0.76)=11.57%