如何输出每个股票?

时间:2017-04-23 02:18:34

标签: java for-loop methods

我必须执行这个程序,我必须显示每个股票的利润计算,但我还必须显示股票总量的利润。我的代码只有它所以显示所有股票的计算:

import java.util.Scanner;

public class KNW_MultipleStockSales
{

  //This method will perform the calculations
  public static double calculator(double numberShare, double purchasePrice, 
                                  double purchaseCommission, double salePrice,
                                  double salesCommission)
  {
    double profit = (((numberShare * salePrice)-salesCommission) - 
                     ((numberShare * purchasePrice) + purchaseCommission));
    return profit;
  }

  //This is where we ask the questions
  public static void main(String[] args)
  {
    //Declare variables
    Scanner scanner = new Scanner(System.in);
    int stock;
    double numberShare;
    double purchasePrice;
    double purchaseCommission;
    double salePrice;
    double saleCommission;
    double profit;
    double total = 0;

    //Ask the questions
    System.out.println("Enter the stocks you have: ");
    stock = scanner.nextInt();

    //For loop for the number stock they are in
    for(int numberStocks=1; numberStocks<=stock; numberStocks++)
    {
      System.out.println("Enter the number of shares for stock " + numberStocks + ": ");
      numberShare = scanner.nextDouble();

      System.out.println("Enter the purchase price" + numberStocks + ": ");
      purchasePrice = scanner.nextDouble();

      System.out.println("Enter the purchase commissioned:" + numberStocks + ": ");
      purchaseCommission = scanner.nextDouble();

      System.out.println("Enter the sale price:" + numberStocks + ": ");
      salePrice = scanner.nextDouble();

      System.out.println("Enter the sales commissioned:" + numberStocks + ": ");
      saleCommission = scanner.nextDouble();

      profit = calculator(numberShare, purchasePrice, purchaseCommission,
                          salePrice, saleCommission);
      total = total + profit;
    }


      //Return if the user made profit or loss
      if(total<0)
      {
        System.out.printf("You made a loss of:$%.2f", total);
      }
      else if(total>0)
      {
        System.out.printf("You made a profit of:$%.2f", total);
      }
      else
      {
        System.out.println("You made no profit or loss.");
      }
  }
}

我怎样才能获得它,以便显示每个股票的利润,所有股票的利润在一起?

1 个答案:

答案 0 :(得分:0)

尝试维护单独的地图以获取利润/亏损。您可能希望接受股票名称作为输入,这将有助于有效管理个股。

 // Map of stock name and profit/loss
 Map<String,Double> profitMap = new HashMap<String,Double>();

计算盈利/亏损后,在地图中添加条目

profitMap.put("stockName", profit);
total = total + profit;

在程序结束时,迭代并显示每张Stock的利润/亏损。

for (Entry<String, Integer> entry : profitMap.entrySet()) {
        System.out.println("Stock Name : " + entry.getKey() + " Profit/loss" + entry.getValue());
    }