在Java中,如何访问arrayLIst中存储的字符串对象?

时间:2017-04-29 03:35:46

标签: java object arraylist

    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;
    }
}

我正在做一个学校项目;用户输入贴纸,股票数量和价格的程序。然后他们可以选择买卖。我遇到的问题是,他们以34.45的价格购买了6股IBM,并希望出售4股;我想更新投资组合中的股票。我想我需要删除购买的原始股票,并将剩余股票作为新的StockHolding。问题是我如何在Portfolio的arrayList中找到String的索引来删除旧的现在已经过时的StockHolding?该项目有一个Calculation类,一个portfolioAction类,Messages类和Account类,使用由教师提供的WidgetView类。这是我的第一个Java学期。谢谢你的帮助。

更新:程序的所有类都在那里。教练希望包含某些课程。我们还没有完成哈希映射,只能使用我们在这一点上涵盖的材料。所以我道歉。 :Output window for sell

我没有收到任何错误消息;我正在使用IntelliJ IDEA。我的问题在截图中。它给了我更新库存但不删除旧库存。我尝试过方法索引而且只是卡住了。但所有类都在这里,它运行没有错误。再次感谢你,对不起,这太长了。

2 个答案:

答案 0 :(得分:0)

根据类别找到字符串的索引..

尝试使用以下方法:

private ArrayList<String> _categories;

private int getCategoryPos(String category) { return _categories.indexOf(category); }

要替换数组列表中的旧值,请使用set:

而不是删除,

_categories.set( your_index, your_item )

希望它有所帮助。

答案 1 :(得分:0)

您的代码有点长,没有规格或样本输出。但要查找和更改库存,您可以使用

Array.Copy(Books, indexToRemove + 1, Books, indexToRemove, BooksCount - indexToRemove - 1);
BooksCount--;
Books[BooksCount] = default(Book); // null?