在Java中,如何访问arrayLIst中存储的string对象? import java.util.ArrayList; 公课档案{ ArrayList myportfolio=新的ArrayList(); int组合化; 国际控股; 公共投资组合(){
在Java中,如何访问arrayLIst中存储的string对象?在Java中,如何访问arrayLIst中存储的string对象? import java.util.ArrayList; 公课档案{ ArrayList myportfolio=新的ArrayList(); int组合化; 国际控股; 公共投资组合(){,java,object,arraylist,Java,Object,Arraylist,在Java中,如何访问arrayLIst中存储的string对象? import java.util.ArrayList; 公课档案{ ArrayList myportfolio=新的ArrayList(); int组合化; 国际控股; 公共投资组合(){ } 公众持股(持股我的股票){ myportfolio.add(String.valueOf(mystock)); } 公共int getSize(){ portfolioSize=myportfolio.size(); 回归组合化; } 公
import java.util.ArrayList;
公课档案{
ArrayList myportfolio=新的ArrayList();
int组合化;
国际控股;
公共投资组合(){
}
公众持股(持股我的股票){
myportfolio.add(String.valueOf(mystock));
}
公共int getSize(){
portfolioSize=myportfolio.size();
回归组合化;
}
公共布尔值isInPortfolio(字符串标记器){
字符串temp=myportfolio.toString();
if(temp.contains(ticker))返回true;
否则返回false;
}
公共空域delaStock(int stockArray){
//字符串temp=myportfolio.toString();
//int tickerloc=温度指数(ticker);
//int dot=温度指数('.',tickerloc);
//字符串stocksum=临时子字符串(tickerloc,点+3);
//myportfolio.remove(stocksum);
}
public int getstockShares(字符串代码){
字符串temp=myportfolio.toString();
int tickerloc=温度指数(ticker);
int colon=temp.indexOf(“:”,tickerloc);
int boughtStr=临时指数(“买入”,tickerloc);
字符串stockShares=临时子字符串(冒号+1,boughtStr-1);
stockShares=stockShares.trim();
int sharesOwned=Integer.parseInt(股票);
投资回报率;
}
公开双getstockPrice(字符串报价器){
字符串temp=myportfolio.toString();
int tickerloc=温度指数(ticker);
int dsign=temp.indexOf(“$”,tickerloc);
int dot=温度指数('.',tickerloc);
字符串orgPrice=临时子字符串(dsign+1,dot+3);
orgPrice=orgPrice.trim();
double purchasePrice=double.parseDouble(orgPrice);
退货价格;
}
公共整数股票长度(字符串代码){
字符串temp=myportfolio.toString();
int tickerloc=温度指数(ticker);
int点=温度指数('.');
字符串存量=临时子字符串(tickerloc,dot+2);
int stockloc=myportfolio.indexOf(股票);
返回stockloc;
}
公共字符串toString(){
字符串摘要=(myportfolio.toString());
返回摘要;
}
}
公营股{
弦乐器;
整数股;
双首字母价格;
双重成本;
双电流值;
双流利润;
双倍流动价格;
公众持股(字符串股票代码、整数股、双首字母价格){
this.ticker=ticker;
this.numberShares=numberShares;
this.initialPrice=初始价格;
}
公共字符串getTicker(字符串标记器){
退票机;
}
double getInitialSharePrice(){
返回初始价格;
}
int getShares(){
返回号码共享;
}
公共双getCurrentSharePrice(){
退货价格;
}
公共双getInitialCost(){
初始成本=数字共享*初始价格;
退货成本;
}
公共双getCurrentValue(){
currentValue=数字共享*当前价格;
返回当前值;
}
公共双getCurrentProfit(){
this.currentProfit=numberShares*(currentPrice-初始价格);
返还此项利润;
}
公共字符串toString(){
字符串摘要=(“股票“+ticker+”:“+numberShares+”以“+initialPrice+'\n')购买);
返回摘要;
}
公开作废setCurrentSharePrice(双重股价){
当前价格=股票价格;
}
}
公共类股票项目{
公共静态void main(字符串[]arg){
PortfolioAction事务=新PortfolioAction();
}
}
公共类计算{
私人股本;
私人双价支付;
专用字符串自动售票机;
私有整数;
私人内部升级共享;
私人双价;
私人双重销售;
私人投资组合;
私人双重价格差异;
公开计算(字符串代码、整数、双倍价格、组合myportfolio){
this.ticker=ticker;
this.num=num;
这个价格=价格;
this.myportfolio=myportfolio;
}
公众股{
this.haveShares=myportfolio.getstockShares(股票代码);
}
public int getHaveShares(){
归还本公司股票;
}
已支付的公共发票(){
pricePaid=myportfolio.getstockPrice(股票代码);
}
公共双GetPricePayed(){
归还此文件。价格已支付;
}
公开发售{
销售=数量*价格;
}
公开发售{
退货;
}
public int getnumShares(){
股票回报率;
}
公共无效设置共享(){
this.updShares=haveShares-num;
}
public int getUpdShares(){
返回此.updShares;
}
公共无效setPriceDiff(){
this.priceDiff=已支付价格-价格;
}
公共双getpriceDiff(){
this.priceDiff=已支付价格-价格;
返回此.priceDiff;
}
}
导入javax.swing.*;
导入java.awt.event.ActionEvent;
公共类PortfolioAction{
私人JLabel jlticker;
私有JTextField jtenertkr;
私人JLabel jlnumShares;
私人JTextField jtenterShares;
私人JLabel jlPrice;
私人JTextField jtenterPrice;
私人JLabel左;
私人JLabel jlCash;
私人JLabel jlCashAmt;
私人JLabel jlRight;
私人JLabel-butLeft;
私人JButton jbsell;
私人JButton jbbuy;
私人JLabel-butRight;
私有的
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;
}
}
myportfolio.set(indexOf(oldStock), newStock)