【问题标题】:Java Sell Method Stock ClassJava 卖出方法股票类
【发布时间】:2014-02-09 16:30:45
【问题描述】:

这是我的作业

我正在尝试编写允许以给定价格出售某些股票的方法 sell。该方法采用两个参数:作为 int 的股票数量和作为双倍的每股价格。该方法返回一个布尔值来指示销售是否成功。例如:

// myStock now has 30 shares at total cost $90.00
boolean success = myStock.sell(5, 4.00);
// sells 5 shares at $4.00 successfully
// myStock now has 25 shares at total cost $70.00
success = myStock.sell(2, 5.00);
// sells 2 shares at $5.00 successfully
// myStock now has 23 shares at total cost $60.00  

My Code :

public static void buy(int numBuyShares, double priceBuyShares)
{
double tempTotalCost = ((double)numBuyShares * priceBuyShares);
totalShares += numBuyShares;
totalCost += priceBuyShares;

}
public static void sell(int numSellShares, double priceSellShares) 
{

 ?????
}

1.) 我如何使用之前的买入股票和成本减去卖出股票和价格?

【问题讨论】:

  • totalShares -= numBuyShares; ?
  • 你有尝试过吗?现在看起来你没有比你之前的问题更多的东西了。 stackoverflow.com/questions/21660916/java-buy-method
  • 如果每股价格可以变化,为什么要存储所有股票的总成本?
  • 我的错。我正在编写一个多线程类程序。我需要做一个买入方法、卖出方法和盈利方法。两种方法的价格和份额都会在 Thread 类中随机生成。

标签: java


【解决方案1】:

我想你想要这样的东西......

public static boolean sell(int numSellShares, double priceSellShares) {
    double sellCost = numSellShares * priceSellShares; // calculate total $
                                                        // to sell

    // assure 2 things:
    // shares to sell does not exceed total # of shares; and
    // total $ to sell does not exceed total cost
    if (numSellShares <= totalShares && sellCost <= totalCost) {
        // subtract #shares and cost from total
        totalShares -= numSellShares;
        totalCost -= sellCost;
        return true; // return success
    }
    // tried to sell more shares or $ than what exists
    else {
        return false; // return failure
    }
}

但话又说回来,不知道你的要求是什么,所以不能确定是什么决定了成功或失败。

【讨论】:

    猜你喜欢
    • 2017-09-26
    • 2013-08-14
    • 1970-01-01
    • 2014-02-23
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多