Assignment 1

Programming Project

Project Details

Background information and description

By definition, a shareholder owns one or more shares of stock in a public or private corporation. A shareholder may own shares in multiple companies, this is known as a portfolio. Shares of stock for the corporation are traded (bought and sold) on the stock market where the price of the stock fluctuates due to supply and demand. A shareholder is not able to trade shares of stock directly themselves but must use the services of an agent, commonly known as a broker or stockbroker, to trade the shares on their behalf. The broker charges the shareholder a fee for each of the trades they transact on their behalf.
In this assignment, your task is to create an object-oriented, menu-driven Java program that implements a limited set off unctionalities (i.e., the program will not be a completely real-world implementation) that a broker can use to buy and sell shares for its customers, generate reports, and retrieve and save data in secondary storage.

In general, your program will need to read data from the keyboard and from certain text files in secondary storage, store the data in appropriate data structures using objects, sort and search the data, and write output data to both the screen and to secondary storage.

Program Requirements/Functionality
the Java program must
a) be object-oriented utilizing the classes as a minimum. Other classes may also be needed to solve the program requirements;
b) be menu-driven. The main menu must have the following menu items:
1. Trade Shares
2. Portfolio Report
3. Save
4. Exit Program
c) be able to process the defined text files.

Program Start Up
When the java program starts it must perform the following file related operations:
d) Read the data from the shareholder.txt file into computer memory into an appropriate array of objects. If the shareholder file does not exist then the user should be informed of this and given the opportunity to provide an alternative filename that contains the shareholder data;
e) Read the data from the portfolios.txt file into computer memory into an appropriate array of objects. If the portfolios file does not exist then the user should be informed of this and given the opportunity to provide an alternative filename that contains the portfolios data;
f) Read the data from the shares.txt file into computer memory into an appropriate array of objects If the sharesfile does not exist then the user should be informed of this and given the opportunity to provide an alternativefilename that contains the shares data.

After processing these three files the program should display the main menu.

Main Menu Item Functionality
The required functionality for each menu item is described as follows:
1. Trade Shares – when this menu option is selected the following actions should be performed by the program:
• Find the customer for which shares are to be traded
• Identify which share stock they wish to trade. If the customer already owns shares in the chosen company then shares may be either bought or sold. However, if they wish to trade in shares which they don’t yet own then shares may only be bought.
• determine if the shares are to be bought or sold for the customer, and how many shares
• transact the trade (ensure your program takes into account all logical validation conditions when doing so).
• generate an on-screen summary of the trade. The summary of the trade must show the customername and address, portfolio ID, current date, share code, company name, number of shares bought orsold, share price, total of the trade. Make sure that this is displayed in a clear and logical format on the screen.
2. Portfolio Report – when this menu option is selected the following actions should be performed:
• Determine if the report is for all customers or for a specific customer
• generate the Portfolio Report for either all customers or the specified customer. The Portfolio Report should have a similar layout to the following example:
PORTFOLIO REPORT for First name Surname
Address
Portfolio #, Report Date

  1. Save – the program must write the portfolios data back to the Portfolios text file.
  2. Exit Program – the program must terminate when this menu item is selected. The program should not terminate until this option is chosen. If the portfolio data has changed since the last save then do not exit the program. Instead, warn the user that they should choose the Save option, then return program control to the main menu.

Text files to be processed

The data that is to be manipulated by your Java program for this assignment is contained in the text filesshareholders.txt, portfolios.txt, and shares.txt. Examples of these text files are found in the zip file for the assignment.
The data within these text files will need to be read into memory by your program so that it may be manipulated to solve many aspects of the required functionality of the assignment. The text files have been created to conform to a particular format. The format for each file is described below:

File: shareholders.txt

This file contains a full record of all customers for the broker. Each line within the file represents an individual customer and has the following format:
Customer ID, Customer Name, Customer Address, Portfolio ID
where each data item is separated by a comma (,).
A brief explanation of each of these data items:

Customer ID: a unique numeric identifier for a customer
Customer Name: the customer name in the format: first name surname
Customer Address: the customer address
Portfolio ID: a unique identifier for the customer share portfolio 

File: portfolios.txt

This file contains a full record of all portfolios for customers. Each line within this file represents an individual portfolio of shares for a shareholder, and has the following format:
Portfolio ID, [Share code, Number of shares] {10}
where each data item is separated by a comma (,). Note: A portfolio can have up to 10 different share stocks hence the Share Code and Number of shares may be repeated up to 10 times.
A brief explanation of each of these data items:
Portfolio ID: a unique identifier for the customer share portfolio
Share code: code used to identify the share stock
Number of Shares: the number of shares for the share held

File: shares.txt

This file contains a full record of all shares that can be traded by the broker. Each line within the file represents a share stock, and has the following format:
Share code, Company Name, price
where each data item is separated by a comma (,).
A brief explanation of each of these data items:
Sharecode: code used to identify the share stock
Company Name: the name of the company of the share code
price: the closing price of the share stock 

Required Classes

To write your solution for this assignment it is a requirement that you write appropriate code for at least the following java Classes:
a) Shareholder
b) Portfolio
c) Share
These classes are described in general terms as follows:
a) Shareholder class: The Shareholder class represents an individual shareholder (customer). The Shareholder class needs data fields for the Customer ID, first name, surname, address, portfolio id. Implement appropriate constructors, accessors, and mutators where necessary and other appropriate methods for this class based upon the general requirements of the assignment specification – that is, you will need to identify if the shareholder class is required to perform any other actions and implement the identified methods in the class.
b) Portfolio class: The Portfolio class represents a collection of one or more Shares that an individual Shareholder owns. The Portfolio class needs data fields for the Portfolio ID, Share Code, the number of shares.
Implement appropriate constructors, accessors, and mutators where necessary and other appropriate methodsfor this class based upon the general requirements of the assignment specification.
c) Share class: The Share class represents an individual Share stock that is traded on the stock market by the broker. The Share class needs data fields for the Share Code, the Company name, the Share price. Implement appropriate constructors, accessors, and mutators where necessary and other appropriate methods for this class based upon the general requirements of the assignment specification – that is, you will need to identify if the share class is required to perform any other actions and implement the identified methods in the class. Apart from the above three classes it is possible that you will also need to write other classes depending upon your solution method. 

Solution 

Asset.java

public class Asset {

protected Share share;

protected int amount;

public Asset(String code, int value) {

share = new Share(code);

amount = value;

}

public Share getShare() {

return share;

}

public String getShareCode() {

return share.getShareCode();

}

public int getAmount() {

return amount;

}

public void setAmount(int number) {

amount = number;

}

public String toString() {

String str = “Share Code: ” + share.getShareCode() + “\nAmount: ” + amount;

return str;

}

} 

Data.java 

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileWriter;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.Scanner;

public class Data {

final static int ARRAY_SIZE = 100;// change array size here

static int totalShareholders, totalShares, totalPortfolios, totalAssets, totalTrades;

static Shareholder[] shareholders = new Shareholder[ARRAY_SIZE];

static Share[] shares = new Share[ARRAY_SIZE];

static Portfolio[] portfolios = new Portfolio[ARRAY_SIZE];

static Asset[] assets = new Asset[ARRAY_SIZE];

static Trade[] trades = new Trade[ARRAY_SIZE];

static String[] portfolioNoList = new String[ARRAY_SIZE];

static int maxList = 0;

public static void loadData() throws FileNotFoundException {

// Read data from file

readShareholderFile();

readShareFile();

readPortfolioFile();

}

public static void readShareholderFile() throws FileNotFoundException {

File myfile = new File(“shareholders.txt”);

Scanner inputFile = new Scanner(myfile);

String[] tokens, name;

int id;

totalShareholders = 0;

// Read until the end of the file.

while (inputFile.hasNext()) {

String line = inputFile.nextLine(); // read the entire line from the file

tokens = line.split(“,”); // split the line after every comma

name = tokens[1].split(” “); // split the name into first and last name

id = Integer.parseInt(tokens[0]); // convert id from string to int

shareholders[totalShareholders] = new Shareholder(id, name[0], name[1], tokens[2], tokens[3]);

totalShareholders++;

}

inputFile.close();

}

public static void readShareFile() throws FileNotFoundException {

File myfile = new File(“shares.txt”);

Scanner inputFile = new Scanner(myfile);

String[] tokens;

totalShares = 0;

// Read until the end of the file.

while (inputFile.hasNext()) {

String line = inputFile.nextLine(); // read the entire line from the file

tokens = line.split(“,”); // split the line after every comma

shares[totalShares] = new Share(tokens[0], tokens[1], Float.parseFloat(tokens[2]));

totalShares++;

}

inputFile.close();

}

public static void readPortfolioFile() throws FileNotFoundException {

File myfile = new File(“portfolios.txt”);

Scanner inputFile = new Scanner(myfile);

String[] tokens;

totalPortfolios = 0;

totalAssets = 0;

// Read until the end of the file.

while (inputFile.hasNext()) {

String line = inputFile.nextLine(); // read the entire line from the file

tokens = line.split(“,”); // split the line after every comma

portfolios[totalPortfolios] = new Portfolio(tokens[0]);

// loop all the shareholder

for (int i = 0; i < totalShareholders; i++) {

// get the portfolio id, if its true

if (shareholders[i].getPortfolioID().equals(tokens[0])) {

// loop the line, and add the asset to the portfolio

for (int j = 1; j < tokens.length; j = j + 2) {

// for each asset create an asset object and store into array object

assets[totalAssets] = new Asset(tokens[j], Integer.parseInt(tokens[j + 1]));

// search the share code that match with asset

for (int k = 0; k < totalShares; k++) {

// if it match bind to asset

if (tokens[j].equals(shares[k].getShareCode())) {

assets[totalAssets].getShare().updateShare(shares[k].getName(), shares[k].getPrice());

}

}

// add the asset and bind it to the portfolio

portfolios[totalPortfolios].addAsset(assets[totalAssets]);

// update the portfolio object in the shareholder

shareholders[i].updatePortfolio(portfolios[totalPortfolios]);

totalAssets++;

}

totalPortfolios++;

}

}

}

inputFile.close();

}

public static void createUniqueList() throws FileNotFoundException {

File myfile = new File(“trades.txt”);

Scanner inputFile = new Scanner(myfile);

String[] tokens;

boolean isUnique = false;

while (inputFile.hasNext()) {

isUnique = false;

String line = inputFile.nextLine(); // read the entire line from the file

tokens = line.split(“,”); // split the line after every comma

if (maxList == 0) {

portfolioNoList[maxList] = tokens[0];

maxList++;

}

for (int i = 0; i < maxList; i++) {

if (portfolioNoList[i].equals(tokens[0])) {

isUnique = true;

}

}

if (!isUnique) {

portfolioNoList[maxList] = tokens[0];

maxList++;

}

}

inputFile.close();

}

public static void processTradeFile() throws IOException {

String[] allFailMessage = new String[100];

String failMessage;

int messageCount = 0;

Shareholder shareholder = null;

// create unique list

createUniqueList();

// create trade report text file

FileWriter successFile = new FileWriter(“tradeReport.txt”);

PrintWriter inputSuccessFile = new PrintWriter(successFile);

// create failed trades text file

FileWriter failFile = new FileWriter(“FailedTrades.txt”);

PrintWriter inputFailFile = new PrintWriter(failFile);

// Success text file title

inputSuccessFile.println(“CUSTOMER TRADE REPORT”);

// use each unique portfolio number run though the trade file

for (int i = 0; i < maxList; i++) {

// find shareholder

shareholder = Shareholder.searchShareholder(portfolioNoList[i]);

// write each portfolio id heading

shareholder.printHeader(inputSuccessFile);

failMessage = loadTradeFile(portfolioNoList[i], inputSuccessFile);

// if return fail message, store into array

if (failMessage != null) {

allFailMessage[messageCount] = failMessage;

messageCount++;

}

}

// use the stored fail message write into failedTrade.txt

for (int j = 0; j < messageCount; j++) {

inputFailFile.println(allFailMessage[j]);

}

inputSuccessFile.close();// close the connection of the write file

inputFailFile.close();// close the connection of the write file

System.out.println(“Trade completed”);

}

public static String loadTradeFile(String shareCode, PrintWriter inputSuccessFile)

throws NumberFormatException, IOException {

String[] tokens;

String errorMessage = null;

File myfile = new File(“trades.txt”);

Scanner inputFile = new Scanner(myfile);

while (inputFile.hasNext()) {

String line = inputFile.nextLine(); // read the entire line from the file

tokens = line.split(“,”); // split the line after every comma

if (tokens[0].equals(shareCode)) {

errorMessage = Trade.processTradeFile(tokens[0], tokens[1], Integer.parseInt(tokens[2]),

inputSuccessFile);

}

}

inputFile.close(); // close the connection of the read file

return errorMessage;

}

public static void updatePortfolioTextFile() throws IOException {

String portfolioStr, assetStr, completeAsset;

Asset[] asset;

// open file

FileWriter writePortfolio = new FileWriter(“portfolios.txt”);

PrintWriter updatePortfolio = new PrintWriter(writePortfolio);

// read each portofolio object

for (int i = 0; i < totalPortfolios; i++) {

completeAsset = “”;

portfolioStr = portfolios[i].getID();

asset = portfolios[i].getAsset();

for (int j = 0; j < portfolios[i].getAssetCount(); j++) {

assetStr = asset[j].getShareCode() + “,” + asset[j].getAmount();

// System.out.println(“i:”+i+”j:”+j+” “+assetStr);

completeAsset = completeAsset + assetStr;

if (j != portfolios[i].getAssetCount() – 1) {

completeAsset = completeAsset + “,”;

}

}

portfolioStr = portfolioStr + “,” + completeAsset;

updatePortfolio.println(portfolioStr);

}

updatePortfolio.close();

System.out.println(“Portfolios updated”);

}

} 

Menu.java 

import java.io.IOException;

import java.util.Scanner;

public class Menu {

static String[] menuItems = { “Trade Shares”, “Portfolio Report”, “Save”, “Exit Program” };

static String[] menuItems2 = { “Trade by Keyboard”, “Trade by File”, “Exit” };

static String[] menuItems4 = { “Buy Share”, “Sell Share”, “Exit” };

static String[] menuItems5 = { “All Customers”, “Select Customer”, “Exit” };

final static int minMenu = 0, minMenu2 = 0, minMenu4 = 0, minMenu5 = 0;

final static int maxMenu = menuItems.length – 1;

final static int maxMenu2 = menuItems2.length – 1;

final static int maxMenu4 = menuItems4.length – 1;

final static int maxMenu5 = menuItems5.length – 1;

static boolean exit, exit2, exit4, exit5;

static Scanner kb = new Scanner(System.in);

static String selectedShareholder, successMessage;

static Shareholder shareholder;

public static void runMenu() throws IOException {

System.out.println(“Welcome to Stock Trading System \n”);

while (!exit) {

displayMenu(menuItems);

int choice = getMenuChoice(minMenu, maxMenu);

performAction(choice);

}

}

public static void runMenu2() throws IOException {

exit2 = false;

while (!exit2) {

displayMenu(menuItems2);

int choice = getMenuChoice(minMenu2, maxMenu2);

performAction2(choice);

}

}

// show buy or sell menu

public static void runMenu4() {

exit4 = false;

while (!exit4) {

displayMenu(menuItems4);

int choice = getMenuChoice(minMenu4, maxMenu4);

performAction4(choice);

}

}

public static void runMenu5() {

exit5 = false;

while (!exit5) {

displayMenu(menuItems5);

int choice = getMenuChoice(minMenu5, maxMenu5);

performAction5(choice);

}

}

public static void displayMenu(String[] menu) {

for (int i = 0; i < menu.length – 1; i++) {

System.out.println((i + 1) + “) ” + menu[i]);

}

System.out.println(“0) ” + menu[menu.length – 1]);

}

public static int getMenuChoice(int min, int max) {

int input = -1;

do {

System.out.println(“Enter your menu choice”);

try {

input = Integer.parseInt(kb.nextLine()); // get user input and convert it into int

} catch (NumberFormatException e) {

System.out.println(“Invalid selection. Numbers only please.”); // error message if user not enter int to

// prevent system crash

}

if (input < min || input > max) {

System.out.println(“Menu choice out of range”);

}

} while (input < min || input > max);

 

return input;

}

public static void performAction(int choice) throws IOException {

switch (choice) {

case 0:

System.out.println(“\nThank you for using our system”);

System.exit(0);

break;

case 1:

// trade shares

runMenu2();

break;

case 2:

// portfolio report

runMenu5();

break;

case 3:

// write all into portfolio.txt

Data.updatePortfolioTextFile();

break;

default:

System.out.println(“Unknown error on menu 1”);

}

}

public static void performAction2(int choice) throws IOException {

switch (choice) {

case 0:

exit2 = true; // back to upper level of menu

break;

case 1:

// trade by keyboard

shareholder = Shareholder.checkID();

runMenu4();

break;

case 2:

// trade by file read file

Data.processTradeFile();

break;

default:

System.out.println(“Unknown error on menu 2”);

}

}

public static void performAction4(int choice) {

switch (choice) {

case 0:

exit4 = true; // back to upper level of menu

break;

case 1:

// handling buy function

successMessage = shareholder.getPortfolio().performBuy();

System.out.println(“\nBuy Summary”);

shareholder.printHeader();

System.out.println(successMessage + “\n”);

break;

case 2:

// handling sell

successMessage = shareholder.getPortfolio().performSell();

System.out.println(“\nSell Summary”);

shareholder.printHeader();

System.out.println(successMessage + “\n”);

// print message

break;

default:

System.out.println(“Unknown error on menu 4”);

}

}

public static void performAction5(int choice) {

switch (choice) {

case 0:

exit5 = true; // back to upper level of menu

break;

case 1:

// print all report

Report.printAll();

break;

case 2:

// print selected shareholder report

Report.printOne();

break;

default:

System.out.println(“Unknown error on menu 5”);

}

}

} 

Portfolio.java 

import java.util.Scanner;

public class Portfolio {

final int ARRAY_SIZE = 100;

private String portfolioID;

private Asset[] assets = new Asset[ARRAY_SIZE];

private Trade[] tradeRecord = new Trade[ARRAY_SIZE];

private int assetCount;

private int tradeCount;

static Scanner kb = new Scanner(System.in);

public Portfolio(String portID) {

portfolioID = portID;

assetCount = 0;

tradeCount = 0;

}

// when add a new asset that not in the portfolio

public void addAsset(Asset newAsset) {

int total;

boolean newItem = true; // initial the newAsset to true

// Search for the new asset that wanted add already in this portfolio

for (int i = 0; i < assetCount; i++) {

// when share id match

if (assets[i].getShareCode() == newAsset.getShareCode()) {

// add validation when new asset amount is negative and more than the current

// asset

total = assets[i].getAmount() + newAsset.getAmount(); // increase or decrease the amount

assets[i].setAmount(total);

assetCount++;

newItem = false;

break;

}

}

if (newItem) {

assets[assetCount] = newAsset;

assetCount++;

}

}

public String getID() {

return portfolioID;

}

public Asset[] getAsset() {

return assets;

}

public int getAssetCount() {

return assetCount;

}

public int getTradeCount() {

return tradeCount;

}

public void setTradeRecord(String code, int amount, Share share, String type) {

tradeRecord[tradeCount] = new Trade(code, amount, type);

tradeRecord[tradeCount].getShare().updateShare(share.getName(), share.getPrice());

tradeCount++;

}

public static Portfolio findPortfolio(String id) {

// loop base on the number of records in the text file

for (int i = 0; i < Data.totalPortfolios; i++) {

// check if there is any id match, also assume that every shareholder the

// portfolio id being created on portfolio.txt

if (Data.portfolios[i].getID().equals(id)) {

return Data.portfolios[i];

}

}

System.out.println(“Portfolio not found”);

return null;

}

public Asset findShareCode(String code) {

 

for (int i = 0; i < assetCount; i++) {

if (assets[i].getShareCode().equals(code)) {

return assets[i];

}

}

// when the code not exist return null, also this is a new share for user to buy

return null;

}

public boolean checkBalance(Asset asset, int amount) {

if (asset.getAmount() < amount) {

return false;

}

return true;

}

public String performSell() {

String input, successMessage = null;

String[] userInput;

do {

System.out.println(“Please enter the share’s code follow by amount you want to sell \neg:JBH,250”);

input = kb.nextLine();

// check input can be split or not

if (Validation.hasTwo(input)) {

userInput = input.split(“,”);

successMessage = sellShare(userInput[0], userInput[1]);

}

} while (successMessage == null);

return successMessage;

}

public String sellShare(String code, String num) {

 

Asset sellAsset;

int amount = 0;

String successMessage, companyName, format;

float price, total;

sellAsset = findShareCode(code);

// if share code is exist

if (sellAsset != null) {

// if amount is an int input

if (Validation.isInt(num)) {

amount = Integer.parseInt(num);

// if the amount not greater than what user current have

if (checkBalance(sellAsset, amount)) {

// deduct the amount

sellAsset.setAmount(sellAsset.getAmount() – amount);

// every success trade will be record into trade class

tradeRecord[tradeCount] = new Trade(code, -amount, “keyboard”);

tradeCount++;

companyName = sellAsset.getShare().getName();

price = sellAsset.getShare().getPrice();

total = amount * price;

format = “%-12s%-52s%-18d%-18.2f%-18.2f%n”;

successMessage = String.format(format, code, companyName, amount, price, total);

return successMessage;

} else {

System.out.println(“Insufficient share amount to sell”);

}

}

} else {

System.out.println(“You don’t have this share in your account”);

}

return null;

}

public String performBuy() {

String input, successMessage = null, code, companyName, format;

String[] userInput;

boolean validatedResult = false;

Asset buyAsset;

Share selectedShare = null;

int amount;

float price, total;

format = “%-12s%-52s%-18d%-18.2f%-18.2f%n”;

do {

System.out.println(“Please enter the share’s code follow by amount you want to buy \neg:JBH,250”);

input = kb.nextLine();

// check input can be split or not

if (Validation.hasTwo(input)) {

userInput = input.split(“,”);

code = userInput[0];

// check if the share code is in the share list

if (Share.checkShareCode(userInput[0])) {

selectedShare = Share.findShare(code);

// check if user enter integer

if (Validation.isInt(userInput[1])) {

amount = Integer.parseInt(userInput[1]); // convert to int

// check the share is new or existed in the portfolio

buyAsset = findShareCode(userInput[0]);

companyName = selectedShare.getName(); // get share company name

price = selectedShare.getPrice(); // get the share price

total = amount * price; // calculate the total price

// add new share in the portfolio

if (buyAsset == null) {

selectedShare = buyShare(userInput[0], amount);

//

successMessage = String.format(format, code, companyName, amount, price, total);

}

// update the existed share in the portfolio

else {

updateExistAsset(buyAsset, amount);

successMessage = String.format(format, code, companyName, amount, price, total);

}

validatedResult = true;

break; // exit the loop if found and performed buying

}

}

}

} while (!validatedResult);

return successMessage;

}

// handle both new or exist shares and call the function according

public Share buyShare(String code, int amount) {

Share shareDetail;

String shareName;

float sharePrice;

shareDetail = Share.findShare(code);

shareName = shareDetail.getName();

sharePrice = shareDetail.getPrice();

// create new asset

assets[assetCount] = new Asset(code, amount);

// update the share detail for the new asset

assets[assetCount].getShare().updateShare(shareName, sharePrice);

assetCount++;

// every success trade will be record into trade class

tradeRecord[tradeCount] = new Trade(code, amount, “keyboard”);

// update the share detail for the new transact

tradeRecord[tradeCount].getShare().updateShare(shareName, sharePrice);

tradeCount++;

return shareDetail;

}

// only handle the asset already in the portfolio

public void updateExistAsset(Asset asset, int amount) {

Share shareDetail;

String shareName;

float sharePrice;

shareDetail = Share.findShare(asset.getShareCode());

shareName = shareDetail.getName();

sharePrice = shareDetail.getPrice();

asset.setAmount(asset.getAmount() + amount);

// every success trade will be record into trade class

tradeRecord[tradeCount] = new Trade(asset.getShareCode(), amount, “keyboard”);

// update the share detail for the new transact

tradeRecord[tradeCount].getShare().updateShare(shareName, sharePrice);

tradeCount++;

}

public String toString() {

String str = “Portfolio ID: ” + portfolioID + “\n”;

for (int i = 0; i < assetCount; i++) {

String str2 = “\nShare Code: ” + assets[i].getShareCode() + “\nAmount of Share: ” + assets[i].getAmount()

+ “\n”;

str += str2;

}

return str;

}

} 

Report.java

public class Report {

public static void printOne() {

Shareholder selectedShareholder = null;

do {

selectedShareholder = Shareholder.checkID();

} while (selectedShareholder == null);

System.out.println(“Portfolio Report”);

printShareholder(selectedShareholder);

}

public static void printAll() {

System.out.println(“Portfolio Report”);

printALLShareholder();

}

// for all

public static void printALLShareholder() {

for (int i = 0; i < Data.totalShareholders; i++) {

printShareholder(Data.shareholders[i]);

}

}

// for individual

public static void printShareholder(Shareholder shareholder) {

int totalNumberOfShare = 0, numberOfShare, assetCount;

float totalShareAmount = 0, shareAmount, sharePrice;

shareholder.printHeader();

String shareCode, companyName, format;

Asset[] asset;

Portfolio portfolio;

assetCount = shareholder.getPortfolio().getAssetCount();

portfolio = shareholder.getPortfolio();

asset = portfolio.getAsset();

format = “%-12s%-52s%-18d%-18.2f%-18.2f%n”;

// print each customer portfolio’s asset detail, included share code, company  name, num of share, share price, total share

for (int i = 0; i < assetCount; i++) {

shareCode = asset[i].getShareCode();

companyName = asset[i].getShare().getName();

numberOfShare = asset[i].getAmount();

sharePrice = asset[i].getShare().getPrice();

shareAmount = numberOfShare * sharePrice;

totalNumberOfShare = totalNumberOfShare + numberOfShare;

totalShareAmount = totalShareAmount + shareAmount;

System.out.format(format, shareCode, companyName, numberOfShare, sharePrice, shareAmount);

}

System.out.format(“%-64s%-36d%-18.2f%n”, “Total”, totalNumberOfShare, totalShareAmount);

System.out.println(“”);

}

} 

Share.java

public class Share {

private String shareCode, name;

private float price;

public Share(String code, String compName, float sharePrice) {

shareCode = code;

name = compName;

price = sharePrice;

}

public Share(String code) {

shareCode = code;

}

public void updateShare(String shareName, float sharePrice) {

name = shareName;

price = sharePrice;

}

public String getName() {

return name;

}

public float getPrice() {

return price;

}

public String getShareCode() {

return shareCode;

}

public static boolean checkShareCode(String code) {

for (int i = 0; i < Data.totalShares; i++) {

if (Data.shares[i].getShareCode().equals(code)) {

return true;

}

}

System.out.println(code + ” cannot be found”);

return false;

}

public static Share findShare(String code) {

for (int i = 0; i < Data.totalShares; i++) {

if (Data.shares[i].getShareCode().equals(code)) {

return Data.shares[i];

}

}

return null;

}

public String toString() {

String str = “Share Code: ” + shareCode + “\nname: ” + name + “\nprice: ” + price;

return str;

}

} 

Shareholder.java 

import java.io.PrintWriter;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Scanner;

public class Shareholder {

private int id;

private String firstName, surname, address;

private Portfolio portfolio;

static Scanner kb = new Scanner(System.in);

public Shareholder(int shareholderID, String fname, String lname, String shareholderAdd, String portID) {

id = shareholderID;

firstName = fname;

surname = lname;

address = shareholderAdd;

portfolio = new Portfolio(portID);

}

public int getID() {

return id;

}

public Portfolio getPortfolio() {

return portfolio;

}

public String getFullName() {

return firstName + ” ” + surname;

}

public String getPortfolioID() {

return portfolio.getID();

}

public void updatePortfolio(Portfolio updatedPort) {

portfolio = updatedPort;

}

// ask user input the id and check it then return the shareholder

public static Shareholder checkID() {

String input;

int userInputID = 0;

Shareholder shareholder;

do {

System.out.println(“Please enter customer’s ID”);

input = kb.nextLine();

if (Validation.isInt(input)) {

userInputID = Integer.parseInt(input);

}

shareholder = Shareholder.searchShareholder(userInputID);

} while (shareholder == null);

return shareholder;

}

// search shareholder by customer id

public static Shareholder searchShareholder(int id) {

for (int i = 0; i < Data.totalShareholders; i++) {

if (Data.shareholders[i].getID() == id) {

return Data.shareholders[i];

}

}

return null;

}

// search shareholder by portfolio id

public static Shareholder searchShareholder(String portfolioID) {

for (int i = 0; i < Data.totalShareholders; i++) {

if (Data.shareholders[i].getPortfolioID().equals(portfolioID)) {

return Data.shareholders[i];

}

}

return null;

}

public void printHeader(PrintWriter inputSuccessFile) {

Date dNow = new Date();

SimpleDateFormat df = new SimpleDateFormat(“dd/MM/yyyy”);

inputSuccessFile.println(“”);

inputSuccessFile.println(“Name:” + firstName + ” ” + surname);

inputSuccessFile.println(“Address:” + address);

inputSuccessFile.println(“Portfolio ID:” + portfolio.getID());

inputSuccessFile.println(“Report Date:” + df.format(dNow));

inputSuccessFile.println(“Share Code\tShares Held\tShares Sold\tShare Bought\tShares Held”);

}

public void printHeader() {

String shareholderDetail;

// get today

Date dNow = new Date();

SimpleDateFormat df = new SimpleDateFormat(“dd/MM/yyyy”);

shareholderDetail = firstName + ” ” + surname + “\n” + address + “\n” + portfolio.getID() + “\n”

+ df.format(dNow) + “\n”;

System.out.println(shareholderDetail);

System.out.format(“%-12s%-52s%-18s%-18s%-18s%n”, “Share Code”, “Company Name”, “Number of Shares”,

“Share Price ($)”, “Shares Total ($)”);

}

public String toString() {

String str = “ID: ” + id + “\nFirstName: ” + firstName + “\nLastName: ” + surname + “\nAddress: ” + address

+ “\nPortfolio ID: ” + portfolio.getID() + “\nTotal Asset: ” + portfolio.getAssetCount()

+ “\nTotal Trade: ” + portfolio.getTradeCount();

return str;

}

} 

Trade.java 

import java.io.IOException;

import java.io.PrintWriter;

import java.text.SimpleDateFormat;

import java.util.Date;

public class Trade extends Asset {

private String inputType;

public Trade(String code, int value, String type) {

super(code, value);

share = new Share(code);

amount = value;

inputType = type;

}

public void setInput(String type) {

inputType = type;

}

public String getType() {

return inputType;

}

public static String processTradeFile(String portNum, String shareCode, int amount, PrintWriter inputSuccessFile)

throws IOException {

Portfolio selectedPortfolio;

Asset asset, newAsset;

int currentAmount = 0;

Boolean shareCodeExist;

Share selectedShare;

String failMessage = null, successMessage;

Date dNow = new Date();

SimpleDateFormat df = new SimpleDateFormat(“dd/MM/yyyy”);

selectedPortfolio = Portfolio.findPortfolio(portNum);

asset = selectedPortfolio.findShareCode(shareCode);

if (asset != null) {

currentAmount = asset.getAmount();

}

shareCodeExist = Share.checkShareCode(shareCode);

if (amount < 0) {

if (asset == null) {

failMessage = portNum + “,” + df.format(dNow) + “,” + shareCode + “,” + amount

+ “,Share not exsit the portfolio”;

return failMessage;

}

else if (currentAmount + amount < 0) {

failMessage = portNum + “,” + df.format(dNow) + “,” + shareCode + “,” + amount

+ “,Insufficient shares to sell”;

return failMessage;

}

else {

successMessage = shareCode + “\t\t” + asset.getAmount() + “\t\t” + (-amount) + “\t\t-\t\t”;

asset.setAmount(currentAmount + amount);

selectedShare = Share.findShare(shareCode);

selectedPortfolio.setTradeRecord(shareCode, amount, selectedShare, “file”);

successMessage = successMessage + asset.getAmount();

inputSuccessFile.println(successMessage);

}

}

else {

if (!shareCodeExist) {

failMessage = portNum + “,” + df.format(dNow) + “,” + shareCode + “,” + amount

+ “Share not exsit in the share list”;

return failMessage;

}

else {

if (asset == null) {

newAsset = new Asset(shareCode, amount);

selectedPortfolio.addAsset(newAsset);

selectedShare = Share.findShare(shareCode);

selectedPortfolio.setTradeRecord(shareCode, amount, selectedShare, “file”);

successMessage = shareCode + “\t\t0\t\t-\t\t” + amount + “\t\t” + newAsset.getAmount();

inputSuccessFile.println(successMessage);

}

else {

successMessage = shareCode + “\t\t” + asset.getAmount() + “\t\t-\t\t” + amount + “\t\t”;

asset.setAmount(currentAmount + amount);

selectedShare = Share.findShare(shareCode);

selectedPortfolio.setTradeRecord(shareCode, amount, selectedShare, “file”);

successMessage = successMessage + asset.getAmount();

inputSuccessFile.println(successMessage);

}

}

}

return failMessage;

}

} 

TradingSystem.java 

import java.io.IOException;

public class TradingSystem {

public static void main(String[] args) throws IOException {

// Load data from text file

Data.loadData();

// Print Menu and program

Menu.runMenu();

}

} 

Validation.java

public class Validation {

 

public static boolean isInt(String input) {

try {

Integer.parseInt(input);

return true;

} catch (NumberFormatException e) {

System.out.print(“Not an integer type input”);

}

return false;

}

public static boolean hasTwo(String input) {

try {

input.split(“,”);

return true;

} catch (NumberFormatException e) {

System.out.print(“The input can’t split into 2 words”);

}

return false;

}

}