2017-04-23 1 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()); 
    } 
관련 문제