我有一个程序,用户在股票对象中输入一个数组列表。股票对象由股票代码,股数和每股成本组成。只要用户不断选择第一个选项,就会提示他们将股票对象添加到不断增长的数组列表中。我希望它能够在用户输入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
您是否需要维护股票行情的每个条目的原始成本,或者只是一个平均运行? –