Stock commission

The problem

Kathryn bought 600 shares of stock at a price of $21.77 per share. She must pay her stockbroker a 2 percent commission for the transaction. Write a program that calculates and display the following:

  • The amount paid for the stock alone (without the commission)
  • The amount of the commission
  • the total amount paid (for the stock plus the commission)

Breaking it down

// Constants
private static final int NUMBER_OF_SHARES = 600;
private static final double STOCK_PRICE = 21.77;
private static final double COMMISSION_PERCENT = 0.02;

public static void main(String[] args) {

    // Calculate the stock cost.
    double stockCost = calculateStockCost(STOCK_PRICE, NUMBER_OF_SHARES);

    // Calculate the commission.
    double commission = calculateCommission(stockCost, COMMISSION_PERCENT);

    // Calculate the total.
    double total = stockCost + commission;

    // Display the results.
    System.out.println("Stock cost: $" + stockCost);
    System.out.println("Commission: $" + commission);
    System.out.println("Total:      $" + total);
}

/**
 * Method should calculate total stock cost
 *
 * @param stockPrice
 * @param commission
 * @return stock cost
 */
static double calculateStockCost(double stockPrice, double commission) {
    return stockPrice * commission;
}

/**
 * Method should calculate commission of a stock
 *
 * @param stockCost
 * @param commissionPercent
 * @return commission
 */
static double calculateCommission(double stockCost, double commissionPercent) {
    return stockCost * commissionPercent;
}

Output

Stock cost: $13062.0
Commission: $261.24
Total:      $13323.24

Unit tests

@Test
public void test_calculateStockCost() {

    double cost = StockCommission.calculateStockCost(10, .10);

    assertEquals(1, cost, 0);
}

@Test
public void test_calculateCommission() {

    double commission = StockCommission.calculateCommission(10, .10);

    assertEquals(1, commission, 0);
}

Level Up

  • Enhance the program to allow for a user to input data
  • Use a DecimalFormatter to format ouput