2017-04-23 2 views
1

私は個々の株の利益の計算を表示する必要がある私はこのプログラムを行う必要がありますが、私はまた、株式の総量の利益を表示する必要があります。私のコードは、それはそれは株式の全てについて計算を表示しています各在庫の出力方法は?

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."); 
     } 
    } 
} 

私はそれがとても個々の株式の利益が一緒にすべての株式の利益を、示します取得できますか?

答えて

0

利益/損失のために別のマップを維持してください。個々の株式を効果的に管理するのに役立つ株式名を入力として受け入れることができます。

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

利益/損失を計算した後、エントリは、あなたのプログラムの終了時

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

をマップ反復処理し、地図から各証券の表示利益/損失に追加します。

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