我有一個程序,用戶在股票對象中輸入一個數組列表。股票對象由股票代碼,股數和每股成本組成。只要用戶不斷選擇第一個選項,就會提示他們將股票對象添加到不斷增長的數組列表中。我希望它能夠在用戶輸入2時顯示最後輸入的250個對象的LIFO平均價格。如何顯示對象的數組列表的平均成本?例如,如果用戶輸入陣列列表中的平均對象
AAPL 200 15
和
AAPL 300 20
,現在他們已經在每個15
和300
更在每個20
買200
股,但我只想第一250
的平均值。這裏是我的代碼:
package stocks;
import java.util.*;
public class Stocks {
private String sym;
private List<Purchase> purchases;
public Stocks(final String symbol) {
this.sym = symbol;
purchases = new ArrayList<Purchase>();
}
public void addPurchase(final int amt, final double cost){
purchases.add(new Purchase(amt,cost));
}
public String getSym(){
return sym;
}
public void setSym(){
this.sym = sym;
}
public double getAvg250() {
int i = 0;
int total = 0;
int shares = 0;
while (i < purchases.size()) {
Purchase p = purchases.get(i);
if (shares + p.getAmt() >= 250) {
total += (250 - shares) * p.getCost();
shares = 250;
break;
}
shares += p.getAmt();
i++;
}
return total * 1.0/shares;
}
class Purchase {
private int amt;
private int cost;
public Purchase(int amt, double cost){
}
public int getAmt() {
return amt;
}
public void setAmt(int amt) {
this.amt = amt;
}
public int getCost() {
return cost;
}
public void setCost(int cost) {
this.cost = cost;
}
public static void main(String[] args) {
int choice = 0;
while (choice == 0){
System.out.println("Enter 1 to input a new stock, or 2 to query a stock's price, 3 to quit: ");
Scanner sc1 = new Scanner (System.in);
choice = sc1.nextInt();
if(choice==1){
ArrayList<Stocks> StocksList = new ArrayList<Stocks>();
Scanner sc2 = new Scanner (System.in);
System.out.println("Please enter the stock symbol: ");
String sym = sc2.next();
System.out.println("Please enter the number of shares: ");
int amt = sc2.nextInt();
System.out.println("Please enter the price per share: ");
double cost = sc2.nextDouble();
Map<String, Stocks> stocks = new HashMap<String, Stocks>();
Stocks s = stocks.get(sym);
if (s == null) {
s = new Stocks(sym);
stocks.put(sym, s);
}
s.addPurchase(amt, cost);
StocksList.add(s);
System.out.println(getAvg250());
}
choice = 0;
if(choice==3){
System.exit(0);
}
}
}
}
}
您準備做什麼?你的名單可以有不同種類的股票,或只有一種? – spinlok
它可以有不同的類型,稍後我將添加一個搜索功能,該功能將顯示用戶搜索的股票的平均成本 – user2921899
您是否需要維護股票行情的每個條目的原始成本,或者只是一個平均運行? –