SlideShare a Scribd company logo
You are to write a GUI program that will allow a user to buy, sell and view stocks in a stock
portfolio.
Objective:
Write a GUI program that maintains a cash balance, list of stock holdings, supports buying and
selling of stocks and displays the current portfolio inventory.
Program Capabilities:
1. Allow a user to buy a stock with a given number of shares and price per share.
2. Display the current portfolio (stock ticker, number of shares, initial price).
3. Update the portfolio display for purchases and sales.
4. Allow the user to sell all of the shares of a given stock.
5. Give the user an initial cash balance, and update and display the balance according to the
user's purchases and sales.
6. Ignore any transaction that causes the cash position to go below $0.
USE OF PREVIOUS StockHolding and PortfolioList LABS IS ADVISED. (I've including my
solutions to these below)
This is my written code from earlier homework:
public class StockHolding {
private String ticker;
private int numShares;
private double initialSharePrice;
private double currentSharePrice;
public StockHolding(String ticker, int numberShares, double initialPrice) {
this.ticker = ticker;
numShares = numberShares;
initialSharePrice = initialPrice;
currentSharePrice = initialPrice;
}
public double getCurrentValue() {
return numShares * getCurrentSharePrice();
}
public double getInitialCost() {
return numShares * getInitialSharePrice();
}
public double getCurrentProfit() {
return getCurrentValue() - getInitialCost();
}
public double getCurrentSharePrice() {
return currentSharePrice;
}
public void setCurrentSharePrice(double currentSharePrice) {
this.currentSharePrice = currentSharePrice;
}
public String getTicker() {
return ticker;
}
public int getShares() {
return numShares;
}
public double getInitialSharePrice() {
return initialSharePrice;
}
@Override
public String toString() {
return "Stock " + ticker + ", " + numShares + ", shares bought at "
+ initialSharePrice + ", current price "
+ currentSharePrice;
}
}
AND
import java.util.ArrayList;
public class PortfolioList {
private ArrayList portfolio;
public PortfolioList() {
portfolio = new ArrayList();
}
public void add(StockHolding stock) {
portfolio.add(stock);
}
public StockHolding find(String ticker) {
for (int i = 0; i < portfolio.size(); i++) {
StockHolding sh = portfolio.get(i);
if (sh.getTicker().equals(ticker)) {
return sh;
}
}
return null;
}
public void remove(String ticker) {
int pos = -1;
for (int i = 0; i < portfolio.size(); i++) {
StockHolding sh = portfolio.get(i);
if (sh.getTicker().equals(ticker)) {
pos = i;
}
}
if (pos != -1) {
portfolio.remove(pos);
}
}
I've been staring at this for two days, and I am lost. Please, any guidance/help would be greatly
appreciated.
Honestly don't even need a full solution, just need something to kick start. A comment skeleton
would help a ton. Thanks!
Solution
SOURCE CODE:
package stock;
public class StockHolding {
private String ticker;
private int numShares;
private double initialSharePrice;
private double currentSharePrice;
public StockHolding(String ticker, int numberShares, double initialPrice) {
this.ticker = ticker;
numShares = numberShares;
initialSharePrice = initialPrice;
currentSharePrice = initialPrice;
}
public double getCurrentValue() {
return numShares * getCurrentSharePrice();
}
public double getInitialCost() {
return numShares * getInitialSharePrice();
}
public double getCurrentProfit() {
return getCurrentValue() - getInitialCost();
}
public double getCurrentSharePrice() {
return currentSharePrice;
}
public void setCurrentSharePrice(double currentSharePrice) {
this.currentSharePrice = currentSharePrice;
}
public String getTicker() {
return ticker;
}
public int getShares() {
return numShares;
}
public double getInitialSharePrice() {
return initialSharePrice;
}
public void setNumShares(int numShares) {
this.numShares = numShares;
}
@Override
public String toString() {
return "Stock " + ticker + ", " + numShares + ", shares bought at "
+ initialSharePrice + ", current price "
+ currentSharePrice;
}
}
--------------------------------------------------------------------------------------------------------------------
---
package stock;
import java.util.ArrayList;
/**
*
* @author Gojkid
*/
public class PortfolioList {
private ArrayList portfolio;
public PortfolioList() {
portfolio = new ArrayList();
}
public void add(StockHolding stock) {
portfolio.add(stock);
}
public StockHolding find(String ticker) {
for (int i = 0; i < portfolio.size(); i++) {
StockHolding sh = portfolio.get(i);
if (sh.getTicker().equals(ticker)) {
return sh;
}
}
return null;
}
public int getPos(StockHolding sh)
{
return portfolio.indexOf(sh);
}
public int getSize()
{
return portfolio.size();
}
public StockHolding getElement(int i) {
return portfolio.get(i);
}
public void remove(String ticker) {
int pos = -1;
for (int i = 0; i < portfolio.size(); i++) {
StockHolding sh = portfolio.get(i);
if (sh.getTicker().equals(ticker)) {
pos = i;
}
}
if (pos != -1) {
portfolio.remove(pos);
}
}
}
--------------------------------------------------------------------------------------------------------------------
---
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* StockTrading.java
*
* Created on Nov 29, 2016, 12:43:57 AM
*/
package stock;
import javax.swing.table.DefaultTableModel;
public class StockTrading extends javax.swing.JFrame {
/** Creates new form StockTrading */
public StockTrading() {
initComponents();
}
@SuppressWarnings("unchecked")
private void initComponents() {
ticker = new javax.swing.JComboBox();
jScrollPane1 = new javax.swing.JScrollPane();
portfolio = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
price = new javax.swing.JTextField();
number = new javax.swing.JSpinner();
buy = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
balance = new javax.swing.JTextField();
sell = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
message = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Stock Trading Program");
ticker.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "A – Agilent
Technologies", "AAPL – Apple Inc.", "BRK.A – Berkshire Hathaway", "C – Citigroup",
"GOOG – Alphabet Inc.", "HOG – Harley-Davidson Inc.", "HPQ – Hewlett-Packard",
"INTC – Intel", "KO – The Coca-Cola Company", "LUV - Southwest Airlines", "MMM –
Minnesota Mining and Manufacturing", "MSFT – Microsoft", "T - AT&T", "TGT – Target
Corporation", "TXN – Texas Instruments", "WMT – Walmart" }));
portfolio.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Ticker", "Number", "Current Price", "Intial Price"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(portfolio);
jLabel1.setText("Ticker :");
jLabel2.setText("Price:");
number.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1),
Integer.valueOf(1), null, Integer.valueOf(1)));
buy.setText("Buy");
buy.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buyActionPerformed(evt);
}
});
jLabel3.setText("Remaining Balance:");
balance.setText("$10000");
sell.setText("Sell");
sell.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sellActionPerformed(evt);
}
});
jLabel4.setText("User's Portfolio");
message.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
message.setText(" ");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 723,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(103, 103, 103)
.addComponent(jLabel3)
.addGap(29, 29, 29)
.addComponent(balance, javax.swing.GroupLayout.PREFERRED_SIZE, 67,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34,
Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 291,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buy)
.addGap(31, 31, 31)
.addComponent(sell))
.addGroup(layout.createSequentialGroup()
.addComponent(ticker, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(30, 30, 30)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(price, javax.swing.GroupLayout.PREFERRED_SIZE, 57,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addComponent(number, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addComponent(message, javax.swing.GroupLayout.PREFERRED_SIZE, 489,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(39, 39, 39))
.addGroup(layout.createSequentialGroup()
.addGap(365, 365, 365)
.addComponent(jLabel4)
.addContainerGap(878, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(33, 33, 33)
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 228,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(67, 67, 67)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(balance, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(102, 102, 102)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ticker, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2)
.addComponent(price, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(number, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(38, 38, 38)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buy)
.addComponent(sell))
.addGap(64, 64, 64)
.addComponent(message)))
.addContainerGap(69, Short.MAX_VALUE))
);
pack();
}
private void buyActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
message.setText("");
price.setText(""+(int)(Math.random()*1000+Math.random()*100+Math.random()*10));
double p = Double.parseDouble(price.getText());
int n = ((Integer)number.getValue()).intValue();
StockHolding sh=new StockHolding((String)ticker.getSelectedItem(),n,p);
if(Double.parseDouble(balance.getText().substring(1))>=(p*n))
{
userPortfolio.add(sh);
bal=Double.parseDouble(balance.getText().substring(1))-(n*p);
balance.setText("$"+(int)bal);
}
else
message.setText("You don't have enough money to buy these shares");
updateTable();
}
private void sellActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
message.setText("");
if(userPortfolio.find((String)ticker.getSelectedItem())!=null)
{
if(userPortfolio.find((String)ticker.getSelectedItem()).getShares()>=((Integer)number.getValue()
).intValue())
{
bal =
Double.parseDouble(balance.getText().substring(1))+userPortfolio.find((String)ticker.getSelecte
dItem()).getCurrentSharePrice()*((Integer)number.getValue()).intValue();
userPortfolio.find((String)ticker.getSelectedItem()).setNumShares(userPortfolio.find((String)tick
er.getSelectedItem()).getShares()-((Integer)number.getValue()).intValue());
balance.setText("$"+(int)bal);
}
else
if(Double.parseDouble(balance.getText().substring(1))==(userPortfolio.find((String)ticker.getSel
ectedItem()).getCurrentSharePrice()*((Integer)number.getValue()).intValue()))
{
bal=Double.parseDouble(balance.getText().substring(1))-
(((Integer)number.getValue()).intValue()*userPortfolio.find((String)ticker.getSelectedItem()).get
CurrentSharePrice());
DefaultTableModel dtm = (DefaultTableModel) portfolio.getModel();
dtm.removeRow(userPortfolio.getPos(userPortfolio.find((String)ticker.getSelectedItem())));
userPortfolio.remove((String)ticker.getSelectedItem());
balance.setText("$"+(int)bal);
}
else
message.setText("You only have
"+userPortfolio.find((String)ticker.getSelectedItem()).getShares()+" shares
of"+ticker.getSelectedItem());
}
else
message.setText("You don't have any "+ticker.getSelectedItem()+" shares");
updateTable();
}
public void updateTable()
{
for (int i = 0; i < userPortfolio.getSize(); i++) {
StockHolding sh = userPortfolio.getElement(i);
if(i <= userPortfolio.getSize())
{
DefaultTableModel dtm = (DefaultTableModel) portfolio.getModel();
dtm.addRow(new Object[]{"", "", "",""});
}
sh.setCurrentSharePrice(sh.getInitialSharePrice()+Math.random()*10);
portfolio.setValueAt(sh.getTicker(), i, 0 );
portfolio.setValueAt(sh.getShares()+"", i, 1 );
portfolio.setValueAt("$"+(int)sh.getCurrentSharePrice(), i, 2 );
portfolio.setValueAt("$"+(int)sh.getInitialSharePrice(), i, 3 );
}
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(StockTrading.class.getName()).log(java.util.logging.Level.S
EVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(StockTrading.class.getName()).log(java.util.logging.Level.S
EVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(StockTrading.class.getName()).log(java.util.logging.Level.S
EVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(StockTrading.class.getName()).log(java.util.logging.Level.S
EVERE, null, ex);
}
//
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new StockTrading().setVisible(true);
}
});
}
private javax.swing.JTextField balance;
private javax.swing.JButton buy;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel message;
private javax.swing.JSpinner number;
private javax.swing.JTable portfolio;
private javax.swing.JTextField price;
private javax.swing.JButton sell;
private javax.swing.JComboBox ticker;
private PortfolioList userPortfolio = new PortfolioList();
private double bal;
}

More Related Content

Similar to You are to write a GUI program that will allow a user to buy, sell a.pdf

Qt Workshop
Qt WorkshopQt Workshop
Qt Workshop
Johan Thelin
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
Erika Susan Villcas
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
Erika Susan Villcas
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
Erika Susan Villcas
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
Erika Susan Villcas
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
Anil Bapat
 
Smart Pointer in C++
Smart Pointer in C++Smart Pointer in C++
Smart Pointer in C++永泉 韩
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns ppt
mkruthika
 
Softwaredesignpatterns ppt-130430202602-phpapp02
Softwaredesignpatterns ppt-130430202602-phpapp02Softwaredesignpatterns ppt-130430202602-phpapp02
Softwaredesignpatterns ppt-130430202602-phpapp02
Nukala Gopala Krishna Murthy
 
Minimum viable product_to_deliver_business_value_v0.4
Minimum viable product_to_deliver_business_value_v0.4Minimum viable product_to_deliver_business_value_v0.4
Minimum viable product_to_deliver_business_value_v0.4Archana Joshi
 
Write a program that mimics the operations of several vending machin.pdf
Write a program that mimics the operations of several vending machin.pdfWrite a program that mimics the operations of several vending machin.pdf
Write a program that mimics the operations of several vending machin.pdf
eyebolloptics
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
Jose Manuel Pereira Garcia
 
Lesson12 other behavioural patterns
Lesson12 other behavioural patternsLesson12 other behavioural patterns
Lesson12 other behavioural patterns
OktJona
 
ITECH 2100 Programming 2 School of Science, Information Te.docx
ITECH 2100 Programming 2 School of Science, Information Te.docxITECH 2100 Programming 2 School of Science, Information Te.docx
ITECH 2100 Programming 2 School of Science, Information Te.docx
christiandean12115
 
show code and all classes with full implementation for these Program S.pdf
show code and all classes with full implementation for these Program S.pdfshow code and all classes with full implementation for these Program S.pdf
show code and all classes with full implementation for these Program S.pdf
AlanSmDDyerl
 
Estructura secuencial -garcia
Estructura secuencial -garciaEstructura secuencial -garcia
Estructura secuencial -garcia
Daneziita Laulate Flores
 
Morgagebuildclasses.netbeans_automatic_buildMorgagebui.docx
Morgagebuildclasses.netbeans_automatic_buildMorgagebui.docxMorgagebuildclasses.netbeans_automatic_buildMorgagebui.docx
Morgagebuildclasses.netbeans_automatic_buildMorgagebui.docx
gilpinleeanna
 
TYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase frameworkTYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase framework
Christian Trabold
 

Similar to You are to write a GUI program that will allow a user to buy, sell a.pdf (20)

Qt Workshop
Qt WorkshopQt Workshop
Qt Workshop
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
 
Smart Pointer in C++
Smart Pointer in C++Smart Pointer in C++
Smart Pointer in C++
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns ppt
 
Softwaredesignpatterns ppt-130430202602-phpapp02
Softwaredesignpatterns ppt-130430202602-phpapp02Softwaredesignpatterns ppt-130430202602-phpapp02
Softwaredesignpatterns ppt-130430202602-phpapp02
 
Minimum viable product_to_deliver_business_value_v0.4
Minimum viable product_to_deliver_business_value_v0.4Minimum viable product_to_deliver_business_value_v0.4
Minimum viable product_to_deliver_business_value_v0.4
 
Write a program that mimics the operations of several vending machin.pdf
Write a program that mimics the operations of several vending machin.pdfWrite a program that mimics the operations of several vending machin.pdf
Write a program that mimics the operations of several vending machin.pdf
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
 
Lesson12 other behavioural patterns
Lesson12 other behavioural patternsLesson12 other behavioural patterns
Lesson12 other behavioural patterns
 
ITECH 2100 Programming 2 School of Science, Information Te.docx
ITECH 2100 Programming 2 School of Science, Information Te.docxITECH 2100 Programming 2 School of Science, Information Te.docx
ITECH 2100 Programming 2 School of Science, Information Te.docx
 
show code and all classes with full implementation for these Program S.pdf
show code and all classes with full implementation for these Program S.pdfshow code and all classes with full implementation for these Program S.pdf
show code and all classes with full implementation for these Program S.pdf
 
Estructura secuencial -garcia
Estructura secuencial -garciaEstructura secuencial -garcia
Estructura secuencial -garcia
 
Morgagebuildclasses.netbeans_automatic_buildMorgagebui.docx
Morgagebuildclasses.netbeans_automatic_buildMorgagebui.docxMorgagebuildclasses.netbeans_automatic_buildMorgagebui.docx
Morgagebuildclasses.netbeans_automatic_buildMorgagebui.docx
 
TYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase frameworkTYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase framework
 
Clean code
Clean codeClean code
Clean code
 

More from jyothimuppasani1

How does an open source operating system like Linux® affect Internet.pdf
How does an open source operating system like Linux® affect Internet.pdfHow does an open source operating system like Linux® affect Internet.pdf
How does an open source operating system like Linux® affect Internet.pdf
jyothimuppasani1
 
Help please!!(Include your modified DList.java source code file in.pdf
Help please!!(Include your modified DList.java source code file in.pdfHelp please!!(Include your modified DList.java source code file in.pdf
Help please!!(Include your modified DList.java source code file in.pdf
jyothimuppasani1
 
how can I replace the Newsfeed text with a custom on in SharePoi.pdf
how can I replace the Newsfeed text with a custom on in SharePoi.pdfhow can I replace the Newsfeed text with a custom on in SharePoi.pdf
how can I replace the Newsfeed text with a custom on in SharePoi.pdf
jyothimuppasani1
 
Hello!This is Java assignment applet.Can someone help me writing.pdf
Hello!This is Java assignment applet.Can someone help me writing.pdfHello!This is Java assignment applet.Can someone help me writing.pdf
Hello!This is Java assignment applet.Can someone help me writing.pdf
jyothimuppasani1
 
For each of the following reseach questions identify the observation.pdf
For each of the following reseach questions identify the observation.pdfFor each of the following reseach questions identify the observation.pdf
For each of the following reseach questions identify the observation.pdf
jyothimuppasani1
 
Find an Eulerian trail in the following graph. Be sure to indicate th.pdf
Find an Eulerian trail in the following graph. Be sure to indicate th.pdfFind an Eulerian trail in the following graph. Be sure to indicate th.pdf
Find an Eulerian trail in the following graph. Be sure to indicate th.pdf
jyothimuppasani1
 
File encryption. [32] Write a program which accepts a filename as a .pdf
File encryption. [32] Write a program which accepts a filename as a .pdfFile encryption. [32] Write a program which accepts a filename as a .pdf
File encryption. [32] Write a program which accepts a filename as a .pdf
jyothimuppasani1
 
Explain the relevance that medical standards of practice have to one.pdf
Explain the relevance that medical standards of practice have to one.pdfExplain the relevance that medical standards of practice have to one.pdf
Explain the relevance that medical standards of practice have to one.pdf
jyothimuppasani1
 
Find the mission and values statements for four different hospita.pdf
Find the mission and values statements for four different hospita.pdfFind the mission and values statements for four different hospita.pdf
Find the mission and values statements for four different hospita.pdf
jyothimuppasani1
 
Did colonial rule freeze colonized societies by preserving old s.pdf
Did colonial rule freeze colonized societies by preserving old s.pdfDid colonial rule freeze colonized societies by preserving old s.pdf
Did colonial rule freeze colonized societies by preserving old s.pdf
jyothimuppasani1
 
Do you think that nonhuman animals have interests Does this mean th.pdf
Do you think that nonhuman animals have interests Does this mean th.pdfDo you think that nonhuman animals have interests Does this mean th.pdf
Do you think that nonhuman animals have interests Does this mean th.pdf
jyothimuppasani1
 
Discuss the importance of recognizing and implementing different ent.pdf
Discuss the importance of recognizing and implementing different ent.pdfDiscuss the importance of recognizing and implementing different ent.pdf
Discuss the importance of recognizing and implementing different ent.pdf
jyothimuppasani1
 
Considering the challenges she is facing, what Anitas plan before .pdf
Considering the challenges she is facing, what Anitas plan before .pdfConsidering the challenges she is facing, what Anitas plan before .pdf
Considering the challenges she is facing, what Anitas plan before .pdf
jyothimuppasani1
 
Data Structure in C++Doubly Linked Lists of ints httpstaffwww.pdf
Data Structure in C++Doubly Linked Lists of ints httpstaffwww.pdfData Structure in C++Doubly Linked Lists of ints httpstaffwww.pdf
Data Structure in C++Doubly Linked Lists of ints httpstaffwww.pdf
jyothimuppasani1
 
Conceptual skills are most important at theSolutionConceptual .pdf
Conceptual skills are most important at theSolutionConceptual .pdfConceptual skills are most important at theSolutionConceptual .pdf
Conceptual skills are most important at theSolutionConceptual .pdf
jyothimuppasani1
 
A variable whose scope is restricted to the method where it was decl.pdf
A variable whose scope is restricted to the method where it was decl.pdfA variable whose scope is restricted to the method where it was decl.pdf
A variable whose scope is restricted to the method where it was decl.pdf
jyothimuppasani1
 
•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf
jyothimuppasani1
 
write the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdfwrite the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdf
jyothimuppasani1
 
What are the factors that contribute to H+ gain or loss How do lung.pdf
What are the factors that contribute to H+ gain or loss How do lung.pdfWhat are the factors that contribute to H+ gain or loss How do lung.pdf
What are the factors that contribute to H+ gain or loss How do lung.pdf
jyothimuppasani1
 
Write down the four (4) nonlinear regression models covered in class,.pdf
Write down the four (4) nonlinear regression models covered in class,.pdfWrite down the four (4) nonlinear regression models covered in class,.pdf
Write down the four (4) nonlinear regression models covered in class,.pdf
jyothimuppasani1
 

More from jyothimuppasani1 (20)

How does an open source operating system like Linux® affect Internet.pdf
How does an open source operating system like Linux® affect Internet.pdfHow does an open source operating system like Linux® affect Internet.pdf
How does an open source operating system like Linux® affect Internet.pdf
 
Help please!!(Include your modified DList.java source code file in.pdf
Help please!!(Include your modified DList.java source code file in.pdfHelp please!!(Include your modified DList.java source code file in.pdf
Help please!!(Include your modified DList.java source code file in.pdf
 
how can I replace the Newsfeed text with a custom on in SharePoi.pdf
how can I replace the Newsfeed text with a custom on in SharePoi.pdfhow can I replace the Newsfeed text with a custom on in SharePoi.pdf
how can I replace the Newsfeed text with a custom on in SharePoi.pdf
 
Hello!This is Java assignment applet.Can someone help me writing.pdf
Hello!This is Java assignment applet.Can someone help me writing.pdfHello!This is Java assignment applet.Can someone help me writing.pdf
Hello!This is Java assignment applet.Can someone help me writing.pdf
 
For each of the following reseach questions identify the observation.pdf
For each of the following reseach questions identify the observation.pdfFor each of the following reseach questions identify the observation.pdf
For each of the following reseach questions identify the observation.pdf
 
Find an Eulerian trail in the following graph. Be sure to indicate th.pdf
Find an Eulerian trail in the following graph. Be sure to indicate th.pdfFind an Eulerian trail in the following graph. Be sure to indicate th.pdf
Find an Eulerian trail in the following graph. Be sure to indicate th.pdf
 
File encryption. [32] Write a program which accepts a filename as a .pdf
File encryption. [32] Write a program which accepts a filename as a .pdfFile encryption. [32] Write a program which accepts a filename as a .pdf
File encryption. [32] Write a program which accepts a filename as a .pdf
 
Explain the relevance that medical standards of practice have to one.pdf
Explain the relevance that medical standards of practice have to one.pdfExplain the relevance that medical standards of practice have to one.pdf
Explain the relevance that medical standards of practice have to one.pdf
 
Find the mission and values statements for four different hospita.pdf
Find the mission and values statements for four different hospita.pdfFind the mission and values statements for four different hospita.pdf
Find the mission and values statements for four different hospita.pdf
 
Did colonial rule freeze colonized societies by preserving old s.pdf
Did colonial rule freeze colonized societies by preserving old s.pdfDid colonial rule freeze colonized societies by preserving old s.pdf
Did colonial rule freeze colonized societies by preserving old s.pdf
 
Do you think that nonhuman animals have interests Does this mean th.pdf
Do you think that nonhuman animals have interests Does this mean th.pdfDo you think that nonhuman animals have interests Does this mean th.pdf
Do you think that nonhuman animals have interests Does this mean th.pdf
 
Discuss the importance of recognizing and implementing different ent.pdf
Discuss the importance of recognizing and implementing different ent.pdfDiscuss the importance of recognizing and implementing different ent.pdf
Discuss the importance of recognizing and implementing different ent.pdf
 
Considering the challenges she is facing, what Anitas plan before .pdf
Considering the challenges she is facing, what Anitas plan before .pdfConsidering the challenges she is facing, what Anitas plan before .pdf
Considering the challenges she is facing, what Anitas plan before .pdf
 
Data Structure in C++Doubly Linked Lists of ints httpstaffwww.pdf
Data Structure in C++Doubly Linked Lists of ints httpstaffwww.pdfData Structure in C++Doubly Linked Lists of ints httpstaffwww.pdf
Data Structure in C++Doubly Linked Lists of ints httpstaffwww.pdf
 
Conceptual skills are most important at theSolutionConceptual .pdf
Conceptual skills are most important at theSolutionConceptual .pdfConceptual skills are most important at theSolutionConceptual .pdf
Conceptual skills are most important at theSolutionConceptual .pdf
 
A variable whose scope is restricted to the method where it was decl.pdf
A variable whose scope is restricted to the method where it was decl.pdfA variable whose scope is restricted to the method where it was decl.pdf
A variable whose scope is restricted to the method where it was decl.pdf
 
•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf
 
write the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdfwrite the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdf
 
What are the factors that contribute to H+ gain or loss How do lung.pdf
What are the factors that contribute to H+ gain or loss How do lung.pdfWhat are the factors that contribute to H+ gain or loss How do lung.pdf
What are the factors that contribute to H+ gain or loss How do lung.pdf
 
Write down the four (4) nonlinear regression models covered in class,.pdf
Write down the four (4) nonlinear regression models covered in class,.pdfWrite down the four (4) nonlinear regression models covered in class,.pdf
Write down the four (4) nonlinear regression models covered in class,.pdf
 

Recently uploaded

Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
bennyroshan06
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
PedroFerreira53928
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 

Recently uploaded (20)

Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 

You are to write a GUI program that will allow a user to buy, sell a.pdf

  • 1. You are to write a GUI program that will allow a user to buy, sell and view stocks in a stock portfolio. Objective: Write a GUI program that maintains a cash balance, list of stock holdings, supports buying and selling of stocks and displays the current portfolio inventory. Program Capabilities: 1. Allow a user to buy a stock with a given number of shares and price per share. 2. Display the current portfolio (stock ticker, number of shares, initial price). 3. Update the portfolio display for purchases and sales. 4. Allow the user to sell all of the shares of a given stock. 5. Give the user an initial cash balance, and update and display the balance according to the user's purchases and sales. 6. Ignore any transaction that causes the cash position to go below $0. USE OF PREVIOUS StockHolding and PortfolioList LABS IS ADVISED. (I've including my solutions to these below) This is my written code from earlier homework: public class StockHolding { private String ticker; private int numShares; private double initialSharePrice; private double currentSharePrice; public StockHolding(String ticker, int numberShares, double initialPrice) { this.ticker = ticker; numShares = numberShares; initialSharePrice = initialPrice; currentSharePrice = initialPrice; } public double getCurrentValue() { return numShares * getCurrentSharePrice(); } public double getInitialCost() {
  • 2. return numShares * getInitialSharePrice(); } public double getCurrentProfit() { return getCurrentValue() - getInitialCost(); } public double getCurrentSharePrice() { return currentSharePrice; } public void setCurrentSharePrice(double currentSharePrice) { this.currentSharePrice = currentSharePrice; } public String getTicker() { return ticker; } public int getShares() { return numShares; } public double getInitialSharePrice() { return initialSharePrice; } @Override public String toString() { return "Stock " + ticker + ", " + numShares + ", shares bought at " + initialSharePrice + ", current price " + currentSharePrice; } } AND import java.util.ArrayList; public class PortfolioList { private ArrayList portfolio; public PortfolioList() { portfolio = new ArrayList();
  • 3. } public void add(StockHolding stock) { portfolio.add(stock); } public StockHolding find(String ticker) { for (int i = 0; i < portfolio.size(); i++) { StockHolding sh = portfolio.get(i); if (sh.getTicker().equals(ticker)) { return sh; } } return null; } public void remove(String ticker) { int pos = -1; for (int i = 0; i < portfolio.size(); i++) { StockHolding sh = portfolio.get(i); if (sh.getTicker().equals(ticker)) { pos = i; } } if (pos != -1) { portfolio.remove(pos); } } I've been staring at this for two days, and I am lost. Please, any guidance/help would be greatly appreciated. Honestly don't even need a full solution, just need something to kick start. A comment skeleton would help a ton. Thanks! Solution SOURCE CODE:
  • 4. package stock; public class StockHolding { private String ticker; private int numShares; private double initialSharePrice; private double currentSharePrice; public StockHolding(String ticker, int numberShares, double initialPrice) { this.ticker = ticker; numShares = numberShares; initialSharePrice = initialPrice; currentSharePrice = initialPrice; } public double getCurrentValue() { return numShares * getCurrentSharePrice(); } public double getInitialCost() { return numShares * getInitialSharePrice(); } public double getCurrentProfit() { return getCurrentValue() - getInitialCost(); } public double getCurrentSharePrice() { return currentSharePrice; } public void setCurrentSharePrice(double currentSharePrice) { this.currentSharePrice = currentSharePrice; } public String getTicker() { return ticker; }
  • 5. public int getShares() { return numShares; } public double getInitialSharePrice() { return initialSharePrice; } public void setNumShares(int numShares) { this.numShares = numShares; } @Override public String toString() { return "Stock " + ticker + ", " + numShares + ", shares bought at " + initialSharePrice + ", current price " + currentSharePrice; } } -------------------------------------------------------------------------------------------------------------------- --- package stock; import java.util.ArrayList; /** * * @author Gojkid */ public class PortfolioList { private ArrayList portfolio; public PortfolioList() { portfolio = new ArrayList(); } public void add(StockHolding stock) { portfolio.add(stock); }
  • 6. public StockHolding find(String ticker) { for (int i = 0; i < portfolio.size(); i++) { StockHolding sh = portfolio.get(i); if (sh.getTicker().equals(ticker)) { return sh; } } return null; } public int getPos(StockHolding sh) { return portfolio.indexOf(sh); } public int getSize() { return portfolio.size(); } public StockHolding getElement(int i) { return portfolio.get(i); } public void remove(String ticker) { int pos = -1; for (int i = 0; i < portfolio.size(); i++) { StockHolding sh = portfolio.get(i); if (sh.getTicker().equals(ticker)) { pos = i; } } if (pos != -1) { portfolio.remove(pos); } } } -------------------------------------------------------------------------------------------------------------------- ---
  • 7. /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * StockTrading.java * * Created on Nov 29, 2016, 12:43:57 AM */ package stock; import javax.swing.table.DefaultTableModel; public class StockTrading extends javax.swing.JFrame { /** Creates new form StockTrading */ public StockTrading() { initComponents(); } @SuppressWarnings("unchecked") private void initComponents() { ticker = new javax.swing.JComboBox(); jScrollPane1 = new javax.swing.JScrollPane(); portfolio = new javax.swing.JTable(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); price = new javax.swing.JTextField(); number = new javax.swing.JSpinner(); buy = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); balance = new javax.swing.JTextField(); sell = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); message = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Stock Trading Program"); ticker.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "A – Agilent Technologies", "AAPL – Apple Inc.", "BRK.A – Berkshire Hathaway", "C – Citigroup", "GOOG – Alphabet Inc.", "HOG – Harley-Davidson Inc.", "HPQ – Hewlett-Packard",
  • 8. "INTC – Intel", "KO – The Coca-Cola Company", "LUV - Southwest Airlines", "MMM – Minnesota Mining and Manufacturing", "MSFT – Microsoft", "T - AT&T", "TGT – Target Corporation", "TXN – Texas Instruments", "WMT – Walmart" })); portfolio.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Ticker", "Number", "Current Price", "Intial Price" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class }; boolean[] canEdit = new boolean [] { false, false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane1.setViewportView(portfolio); jLabel1.setText("Ticker :"); jLabel2.setText("Price:"); number.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1))); buy.setText("Buy"); buy.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buyActionPerformed(evt);
  • 9. } }); jLabel3.setText("Remaining Balance:"); balance.setText("$10000"); sell.setText("Sell"); sell.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { sellActionPerformed(evt); } }); jLabel4.setText("User's Portfolio"); message.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); message.setText(" "); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(30, 30, 30) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 723, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(103, 103, 103) .addComponent(jLabel3) .addGap(29, 29, 29) .addComponent(balance, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
  • 10. .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 291, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(buy) .addGap(31, 31, 31) .addComponent(sell)) .addGroup(layout.createSequentialGroup() .addComponent(ticker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(30, 30, 30) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(price, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(33, 33, 33) .addComponent(number, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addComponent(message, javax.swing.GroupLayout.PREFERRED_SIZE, 489, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(39, 39, 39)) .addGroup(layout.createSequentialGroup() .addGap(365, 365, 365) .addComponent(jLabel4) .addContainerGap(878, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(33, 33, 33) .addComponent(jLabel4) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(67, 67, 67)
  • 11. .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(balance, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addGap(102, 102, 102) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ticker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2) .addComponent(price, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(number, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addGap(38, 38, 38) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(buy) .addComponent(sell)) .addGap(64, 64, 64) .addComponent(message))) .addContainerGap(69, Short.MAX_VALUE)) ); pack(); } private void buyActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: message.setText(""); price.setText(""+(int)(Math.random()*1000+Math.random()*100+Math.random()*10)); double p = Double.parseDouble(price.getText()); int n = ((Integer)number.getValue()).intValue(); StockHolding sh=new StockHolding((String)ticker.getSelectedItem(),n,p); if(Double.parseDouble(balance.getText().substring(1))>=(p*n)) { userPortfolio.add(sh); bal=Double.parseDouble(balance.getText().substring(1))-(n*p);
  • 12. balance.setText("$"+(int)bal); } else message.setText("You don't have enough money to buy these shares"); updateTable(); } private void sellActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: message.setText(""); if(userPortfolio.find((String)ticker.getSelectedItem())!=null) { if(userPortfolio.find((String)ticker.getSelectedItem()).getShares()>=((Integer)number.getValue() ).intValue()) { bal = Double.parseDouble(balance.getText().substring(1))+userPortfolio.find((String)ticker.getSelecte dItem()).getCurrentSharePrice()*((Integer)number.getValue()).intValue(); userPortfolio.find((String)ticker.getSelectedItem()).setNumShares(userPortfolio.find((String)tick er.getSelectedItem()).getShares()-((Integer)number.getValue()).intValue()); balance.setText("$"+(int)bal); } else if(Double.parseDouble(balance.getText().substring(1))==(userPortfolio.find((String)ticker.getSel ectedItem()).getCurrentSharePrice()*((Integer)number.getValue()).intValue())) { bal=Double.parseDouble(balance.getText().substring(1))- (((Integer)number.getValue()).intValue()*userPortfolio.find((String)ticker.getSelectedItem()).get CurrentSharePrice()); DefaultTableModel dtm = (DefaultTableModel) portfolio.getModel(); dtm.removeRow(userPortfolio.getPos(userPortfolio.find((String)ticker.getSelectedItem()))); userPortfolio.remove((String)ticker.getSelectedItem()); balance.setText("$"+(int)bal); } else message.setText("You only have
  • 13. "+userPortfolio.find((String)ticker.getSelectedItem()).getShares()+" shares of"+ticker.getSelectedItem()); } else message.setText("You don't have any "+ticker.getSelectedItem()+" shares"); updateTable(); } public void updateTable() { for (int i = 0; i < userPortfolio.getSize(); i++) { StockHolding sh = userPortfolio.getElement(i); if(i <= userPortfolio.getSize()) { DefaultTableModel dtm = (DefaultTableModel) portfolio.getModel(); dtm.addRow(new Object[]{"", "", "",""}); } sh.setCurrentSharePrice(sh.getInitialSharePrice()+Math.random()*10); portfolio.setValueAt(sh.getTicker(), i, 0 ); portfolio.setValueAt(sh.getShares()+"", i, 1 ); portfolio.setValueAt("$"+(int)sh.getCurrentSharePrice(), i, 2 ); portfolio.setValueAt("$"+(int)sh.getInitialSharePrice(), i, 3 ); } } public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } }
  • 14. } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(StockTrading.class.getName()).log(java.util.logging.Level.S EVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(StockTrading.class.getName()).log(java.util.logging.Level.S EVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(StockTrading.class.getName()).log(java.util.logging.Level.S EVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(StockTrading.class.getName()).log(java.util.logging.Level.S EVERE, null, ex); } // /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new StockTrading().setVisible(true); } }); } private javax.swing.JTextField balance; private javax.swing.JButton buy; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel message; private javax.swing.JSpinner number; private javax.swing.JTable portfolio; private javax.swing.JTextField price; private javax.swing.JButton sell; private javax.swing.JComboBox ticker; private PortfolioList userPortfolio = new PortfolioList();