Solution :
public class {
private stockName, ;
private nShares;
private price;
public
{
this.stockName = "";
this.purchaseDate = "";
this.nShares = 0;
this.price = 0.0;
}
public Stock(String stockName, String purchaseDate, int nShares, double price) {
this.stockName = stockName;
this.purchaseDate = purchaseDate;
this.nShares = nShares;
this.price = price;
}
public String getStockName() {
return stockName;
}
public void setStockName(String stockName) {
this.stockName = stockName;
}
public String getPurchaseDate() {
return purchaseDate;
}
public void setPurchaseDate(String purchaseDate) {
this.purchaseDate = purchaseDate;
}
public int getnShares() {
return nShares;
}
public void setnShares(int nShares) {
this.nShares = nShares;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String toString()
{
return("Stock name: " + this.stockName + "\nPurchase date: " + this.purchaseDate
+ "\nNumber of shares of stock: " + this.nShares + "\nPrice: $" + String.format("%,.2f", this.price));
}
public void printStock()
{
System.out.println("Stock name: " + this.stockName + "\nPurchase date: " + this.purchaseDate
+ "\nNumber of shares of stock: " + this.nShares + "\nPrice: $" + String.format("%,.2f", this.price)
+ "\n");
}
}
StockTester.java (Driver class)
import File;
import FileException;
import ArrayList;
import Scanner;
class StockTester {
private static final String FILENAME = "StockInfocsv";
public static main( args)
{
ArrayList dataStock = (FILENAME);
System.out.println("Initial stocks:");
for(Stock s : dataStock)
s.printStock();
System.out.println("Adding a new Stock object to the list..");
Stock newStock = new Stock("Gamma", "03/01/20", 100, 50.5);
dataStock.add(newStock);
System.out.println("\nStocks after adding the new Stock..");
for(Stock s : dataStock)
s.printStock();
Stock targetStock = dataStock.get(3);
double reqReturn = requiredReturn(targetStock, 4000, 3);
System.out.println("Required rate of return = " + String.format("%.2f", reqReturn) + "%");
}
private static ArrayList<Stock> readData(String filename)
{
ArrayList<Stock> stocks = new ArrayList<>();
Scanner fileReader;
try
{
fileReader = new Scanner(new File(filename));
while(fileReader.hasNextLine())
{
String[] data = fileReader.nextLine().trim().split(",");
String stockName = data[0];
String purchaseDate = data[1];
int nShares = Integer.parseInt(data[2]);
double price = Double.parseDouble(data[3]);
stocks.add(new (stockName, , nShares, price));
}
fileReader.close();
}catch(FileNotFoundException fnfe){
System.out.println(filename + " cannot be found!");
System.exit(0);
}
return stocks;
}
private static double requiredReturn(Stock s, double targetPrice, int years)
{
double reqReturn;
double initialPrice = s.getPrice() * s.getnShares();
reqReturn = ((targetPrice - initialPrice) / initialPrice * years) * 100;
return reqReturn;
}
}