import java.util.ArrayList;
public class Portfolio {
ArrayList<String> myportfolio = new ArrayList<>();
int portfolioSize;
int holding;
public Portfolio(){
}
public void addStockHolding(StockHolding mystock){
myportfolio.add(String.valueOf(mystock));
}
public int getSize(){
portfolioSize = myportfolio.size();
return portfolioSize;
}
public boolean isInPortfolio(String ticker){
String temp = myportfolio.toString();
if (temp.contains(ticker)) return true;
else return false;
}
public void delaStock(int stockArray){
// String temp = myportfolio.toString();
//int tickerloc = temp.indexOf(ticker);
//int dot = temp.indexOf('.', tickerloc);
//String stocksumm = temp.substring(tickerloc, dot+3);
//myportfolio.remove(stocksumm);
}
public int getstockShares(String ticker){
String temp = myportfolio.toString();
int tickerloc = temp.indexOf(ticker);
int colon = temp.indexOf(':', tickerloc);
int boughtStr = temp.indexOf("bought", tickerloc);
String stockShares = temp.substring(colon+1, boughtStr-1);
stockShares = stockShares.trim();
int sharesOwned = Integer.parseInt(stockShares);
return sharesOwned;
}
public double getstockPrice(String ticker){
String temp = myportfolio.toString();
int tickerloc = temp.indexOf(ticker);
int dsign = temp.indexOf('$', tickerloc);
int dot = temp.indexOf('.', tickerloc);
String orgPrice = temp.substring(dsign+1, dot+3);
orgPrice = orgPrice.trim();
double purchasePrice = Double.parseDouble(orgPrice);
return purchasePrice;
}
public int stockLength(String ticker){
String temp = myportfolio.toString();
int tickerloc = temp.indexOf(ticker);
int dot = temp.indexOf('.');
String stock = temp.substring(tickerloc, dot +2);
int stockloc = myportfolio.indexOf(stock);
return stockloc;
}
public String toString(){
String summary = (myportfolio.toString());
return summary;
}
}
public class StockHolding {
String ticker;
int numberShares;
double initialPrice;
double initialCost;
double currentValue;
double currentProfit;
double currentPrice;
public StockHolding(String ticker, int numberShares, double initialPrice){
this.ticker = ticker;
this.numberShares = numberShares;
this.initialPrice = initialPrice;
}
public String getTicker(String ticker){
return ticker;
}
double getInitialSharePrice(){
return initialPrice;
}
int getShares(){
return numberShares;
}
public double getCurrentSharePrice(){
return currentPrice;
}
public double getInitialCost(){
initialCost = numberShares * initialPrice;
return initialCost;
}
public double getCurrentValue(){
currentValue = numberShares * currentPrice ;
return currentValue;
}
public double getCurrentProfit(){
this.currentProfit = numberShares * (currentPrice - initialPrice);
return this.currentProfit;
}
public String toString(){
String summary = ("Stock " + ticker + ": " + numberShares + " bought at $ " + initialPrice + '\n');
return summary;
}
public void setCurrentSharePrice(double sharePrice){
currentPrice = sharePrice;
}
}
public class StockProject {
public static void main(String[] arg){
PortfolioAction transactions = new PortfolioAction();
}
}
public class Calculations {
private int haveShares;
private double pricePaid;
private String ticker;
private int num;
private int updShares;
private double price;
private double sale;
private Portfolio myportfolio;
private double priceDiff;
public Calculations(String ticker, int num, double price, Portfolio myportfolio){
this.ticker = ticker;
this.num = num;
this.price = price;
this.myportfolio = myportfolio;
}
public void setHaveShares() {
this.haveShares = myportfolio.getstockShares(ticker);
}
public int getHaveShares(){
return this.haveShares;
}
public void setPricePaid(){
pricePaid = myportfolio.getstockPrice(ticker);
}
public double getPricePaid(){
return this.pricePaid;
}
public void setSale(){
sale = num * price;
}
public double getSale(){
return sale;
}
public int getnumShares(){
return haveShares;
}
public void setUpdShares(){
this.updShares = haveShares - num;
}
public int getUpdShares(){
return this.updShares;
}
public void setPriceDiff(){
this.priceDiff = pricePaid - price;
}
public double getpriceDiff(){
this.priceDiff = pricePaid - price;
return this.priceDiff;
}
}
import javax.swing.*;
import java.awt.event.ActionEvent;
public class PortfolioAction {
private JLabel jlticker;
private JTextField jtenterTkr;
private JLabel jlnumShares;
private JTextField jtenterShares;
private JLabel jlPrice;
private JTextField jtenterPrice;
private JLabel jlLeft;
private JLabel jlCash;
private JLabel jlCashAmt;
private JLabel jlRight;
private JLabel butLeft;
private JButton jbsell;
private JButton jbbuy;
private JLabel butRight;
private JTextArea jtsummary;
Portfolio myportfolio = new Portfolio();
Account myaccount = new Account();
public PortfolioAction(){
Messages.getDisclaimer();
WidgetView wv = new WidgetView();
jlticker = new JLabel(" Stock Ticker "); //16
jtenterTkr = new JTextField(" "); //25
jlnumShares = new JLabel(" Number of Shares: "); //21
jtenterShares = new JTextField(" "); //25
jlPrice = new JLabel(" Price per Share: "); //21
jtenterPrice = new JTextField(" "); //25
jlLeft = new JLabel(" "); //65
jlCash = new JLabel(" Cash: $ "); //11
jlCashAmt = new JLabel(" 1000.00 " ); //11
jlRight = new JLabel(" "); //65
butLeft = new JLabel(" "); //60
jbsell = new JButton(" Sell ");
jbbuy = new JButton(" Buy ");
butRight = new JLabel(" ");
jtsummary = new JTextArea();
ButtonSell sellaction = new ButtonSell(jtenterTkr, jtenterShares, jtenterPrice, jlCashAmt, jtsummary);
ButtonBuy buyaction = new ButtonBuy(jtenterTkr, jtenterShares, jtenterPrice, jlCashAmt, jtsummary);
jbsell.addActionListener(sellaction);
jbbuy.addActionListener(buyaction);
wv.add(jlticker);
wv.add(jtenterTkr);
wv.add(jlnumShares);
wv.add(jtenterShares);
wv.add(jlPrice);
wv.add(jtenterPrice);
wv.add(jlLeft);
wv.add(jlCash);
wv.add(jlCashAmt);
wv.add(jlRight);
wv.add(butLeft);
wv.add(jbsell);
wv.add(jbbuy);
wv.add(butRight);
wv.add(jtsummary);
}
class ButtonSell extends WidgetViewActionEvent {
private JTextField enterTkr;
private JTextField enterShares;
private JTextField enterPrice;
private JLabel balance;
private JTextArea summary;
private boolean tkrLoc;
private int num;
private double price;
private String currBal;
private int previousShares;
private String ticker;
private double priceDiff;
private int haveShares;
private String salesummary;
public ButtonSell(JTextField jtenterTkr, JTextField jtenterShares, JTextField jtenterPrice, JLabel jlCashAmt, JTextArea jtSummary) {
enterTkr = jtenterTkr;
enterShares = jtenterShares;
enterPrice = jtenterPrice;
balance = jlCashAmt;
summary = jtsummary;
}
@Override
public void actionPerformed(ActionEvent e) {
this.ticker = enterTkr.getText();
this.ticker = ticker.trim();
try {
String numShares = enterShares.getText();
numShares = numShares.trim();
this.num = Integer.parseInt(numShares);
String getPrice = enterPrice.getText();
getPrice = getPrice.trim();
this.price = Double.parseDouble(getPrice);
String currBal = balance.getText();
this.currBal = currBal.trim();
}catch
(NumberFormatException ex) {
Messages.getNumErrMess();
}catch (NullPointerException ex){
Messages.getnotOwned();
}finally {
this.tkrLoc = myportfolio.isInPortfolio(ticker);
if (this.tkrLoc == false) {
Messages.getnotOwned();
} else{
Calculations sellStocks = new Calculations(ticker, num, price, myportfolio);
sellStocks.setHaveShares();
sellStocks.setPricePaid();
sellStocks.setUpdShares();
sellStocks.setPriceDiff();
sellStocks.setSale();
this.previousShares = sellStocks.getnumShares();
if(this.num > this.previousShares){
Messages.lowStockMsg();
balance.setText(currBal);
enterTkr.setText(" "); //25
enterShares.setText(" "); //25
enterPrice.setText(" "); //25
}else {
double sales = sellStocks.getSale();
myaccount.creditAccount(sales);
double newBal = myaccount.getBalance();
int holding = myportfolio.stockLength(ticker);
myportfolio.delaStock(holding);
int updShares = sellStocks.getUpdShares();
double pricePaid = sellStocks.getPricePaid();
StockHolding mystock = new StockHolding(ticker,updShares, pricePaid);
myportfolio.addStockHolding( mystock);
String bal = String.format("%.2f", newBal);
balance.setText(bal);
enterTkr.setText(" "); //25
enterShares.setText(" "); //25
enterPrice.setText(" "); //25
priceDiff = sellStocks.getpriceDiff();
haveShares = sellStocks.getHaveShares();
if (this.priceDiff < 0) {
double profit = priceDiff * haveShares* -1;
String hasProfit = String.format("%.2f" , profit);
salesummary = ("You made a profit of " + hasProfit);
} else if (this.priceDiff > 0) {
double loss = priceDiff * haveShares* -1;
String hasLoss = String.format("%.2f" , loss);
salesummary = ("You had a loss of " + hasLoss);
} else {
salesummary = "You have broke even.";
}
summary.setText(salesummary + '\n' + myportfolio.toString());
}
}
}
}
}
class ButtonBuy extends WidgetViewActionEvent {
private JTextField enterTkr;
private JTextField enterShares;
private JTextField enterPrice;
private JLabel balance;
private JTextArea summary;
public ButtonBuy(JTextField jtenterTkr, JTextField jtenterShares, JTextField jtenterPrice, JLabel jlCashAmt, JTextArea jtsummary) {
enterTkr = jtenterTkr;
enterShares = jtenterShares;
enterPrice = jtenterPrice;
balance = jlCashAmt;
summary = jtsummary;
}
@Override
public void actionPerformed(ActionEvent e) {
String ticker = enterTkr.getText();
ticker = ticker.trim();
try {
String numShares = enterShares.getText();
numShares = numShares.trim();
int num = Integer.parseInt(numShares);
String getPrice = enterPrice.getText();
getPrice = getPrice.trim();
double price = Double.parseDouble(getPrice);
double availCash = Double.parseDouble(balance.getText());
if ((price * num) > availCash) {
Messages.getMoneyMess();
}
else {
StockHolding mystock = new StockHolding(ticker, num, price);
myportfolio.addStockHolding(mystock);
double cost = mystock.getInitialCost();
myaccount.debitAccount(cost);
double newBal = myaccount.getBalance();
String bal = String.format("%.2f", newBal);
balance.setText(bal);
enterTkr.setText(" "); //25
enterShares.setText(" "); //25
enterPrice.setText(" "); //25
summary.setText(myportfolio.toString());
}
}
catch (NumberFormatException ex) {
Messages.getNumErrMess();
}
}
}
}
import javax.swing.JOptionPane;
public class Messages {
static String notEnuffFunds = "Transaction denied: Not enough Funds";
static String errNum = "Error: Number of Shares and Share price must be numbers only";
static String warn = "Warning";
static String noStock = "Stock not available to sell.";
static String disclaim = "Disclaimer";
static String disclosure = "This program is for entertainment purposes only. The account on this program does not represent" +
" any money in the real world nor does this predict any profit or loss on stocks you purchase in the real world.";
static String lowStock = "Not that meaning stock to sell";
public Messages(){
}
public static void getNumErrMess(){
JOptionPane.showMessageDialog(null, errNum, warn, JOptionPane.WARNING_MESSAGE);
}
public static void getMoneyMess(){
JOptionPane.showMessageDialog(null, notEnuffFunds, warn, JOptionPane.WARNING_MESSAGE);
}
public static void getnotOwned(){
JOptionPane.showMessageDialog(null, noStock, warn, JOptionPane.WARNING_MESSAGE);
}
public static void getDisclaimer(){
JOptionPane.showMessageDialog(null, disclosure, disclaim, JOptionPane.INFORMATION_MESSAGE);
}
public static void lowStockMsg(){
JOptionPane.showMessageDialog(null, lowStock, warn, JOptionPane.WARNING_MESSAGE);
}
}
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* A really simple class to display Swing widgets in a FlowLayout GUI.
* <p>
*
* @author parks
*/
public class WidgetView {
public static final int DEFAULT_X_SIZE = 600;
public static final int DEFAULT_Y_SIZE = 400;
private JFrame jframe;
private JPanel anchor;
private boolean userClicked = false;
private Lock lock;
private Condition waitingForUser;
private JComponent userInputComponent = null;
private ActionListener eventHandler;
/**
* Default constructor will display an empty JFrame that has a Flow layout
* JPanel as its content pane and initialize the frame to a default size.
*/
public WidgetView() {
this(DEFAULT_X_SIZE, DEFAULT_Y_SIZE);
}
/**
* Constructor will display an empty JFrame that has a Flow layout
* JPanel as its content pane and initialize the frame to a given size.
*/
public WidgetView(int pixelSizeInX, int pixelSizeInY) {
lock = new ReentrantLock();
waitingForUser = lock.newCondition();
// lambda expression requires Java 8
// eventHandler = e -> {
// if (e.getSource() != userInputComponent) {
// return;
// }
// lock.lock();
// userClicked = true;
// waitingForUser.signalAll();
// lock.unlock();
// };
//* java 7 solution
eventHandler = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() != userInputComponent) {
return;
}
lock.lock();
userClicked = true;
waitingForUser.signalAll();
lock.unlock();
}
};
jframe = new JFrame();
anchor = new JPanel();
jframe.setContentPane(anchor);
jframe.setSize(pixelSizeInX, pixelSizeInY);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setVisible(true);
}
/**
* Add a Swing widget to the GUI.
*
* @param jcomp Swing widget (subclasses of JComponent--like JLabel and
* JTextField) to be added to the JFrame
*/
public void add(JComponent jcomp) {
anchor.add(jcomp);
jframe.setContentPane(anchor);
}
/**
* Add an Abstract Button (like a JButton) to the JFrame. Create an action
* listener to wait (suspend the caller) until it is clicked.
*
* @param absButton Button (like a JButton) to add to the JFrame
*/
public void addAndWait(AbstractButton absButton) {
userInputComponent = absButton;
absButton.addActionListener(eventHandler);
addWait(absButton);
}
/**
* Add a JTextField to the JFrame, and wait for the user to put the cursor
* in the field and click Enter. The caller is suspended until enter is
* clicked.
*
* @param jTextField Field to add to the JFrame
*/
public void addAndWait(JTextField jTextField) {
userInputComponent = jTextField;
jTextField.addActionListener(eventHandler);
addWait(jTextField);
}
private void addWait(JComponent jcomp) {
add(jcomp);
lock.lock();
try {
while (!userClicked) {
waitingForUser.await();
}
}
catch (InterruptedException e1) {
System.err.println("WidgetView reports that something really bad just happened");
e1.printStackTrace();
System.exit(0);
}
userClicked = false;
waitingForUser.signalAll();
lock.unlock();
}
}
import java.awt.event.ActionListener;
public abstract class WidgetViewActionEvent implements ActionListener {
}
public class Account {
double availableBalance = 1000.00;
public Account(){
}
public void debitAccount(double cost){
availableBalance -= cost;
}
public void creditAccount(double sale){
availableBalance += sale;
}
public double getBalance (){
return availableBalance;
}
}
I am working on a school project; a program that has the user enter a sticker, number of stocks and the price. then they have the option to buy and sell. The problem I am having is that say they bought 6 shares of IBM at 34.45 and want to sell 4 of them; I want to update the stock in the portfolio. I figured I would need to delete the original stock bought and put in the remaining stock as a new StockHolding. The problem is how do I find the index of the String in the arrayList of Portfolio to delete the old now out-dated StockHolding? The project has a Calculation class, a portfolioAction class, Messages class, and Account class, with the use of a WidgetView class that was supplied by the teacher. It is my first semester of Java. Thanks for any help.
updated: all the classes for the program are there now. The instructor wanted the inclusion of certain classes. We have not done hash maps and can only use the materials we have covered to this point. So I apologize. : Output window for sell
I do not get any error messages; I am using IntelliJ IDEA. My problem is in the screenshot. It gives me the update stock but doesn't delete the old one. I have tried index of methods and am just stuck. But all the classes are here and it runs without error. Thank you again and sorry this is so lengthy.