【发布时间】:2014-05-10 04:54:45
【问题描述】:
我有一个程序,用户将股票对象输入到数组列表中。股票对象由股票代码、股票数量和每股成本组成。只要用户继续选择第一个选项,就会提示他们将库存对象添加到不断增长的数组列表中。我希望这样当用户输入 2 时,我希望显示最后输入的 250 个对象的 LIFO 平均价格。如何显示对象数组列表的平均成本?例如,如果用户输入
AAPL 200 15
和
AAPL 300 20
,现在他们以15 的价格购买了200 的股票,并以20 的价格购买了更多300,但我只想要第一个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);
}
}
}
}
}
【问题讨论】:
-
你到底想做什么?您的清单可以包含不同种类的股票,还是只有一种?
-
它可以有不同的种类,稍后我将添加一个搜索功能,它将显示用户搜索的股票的平均成本
-
您是否需要为股票代码的每个条目保持原始成本,还是只是一个运行平均值?
-
用户输入2时会计算平均值,所以最近的250个分享会被平均。
标签: java