gpt4 book ai didi

java - 每只股票如何输出?

转载 作者:太空宇宙 更新时间:2023-11-04 11:33:12 24 4
gpt4 key购买 nike

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

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

如何才能显示每只股票的利润以及所有股票的利润?

最佳答案

尝试维护一个单独的损益 map 。您可能需要接受股票名称作为输入,这将有助于有效管理个股。

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

计算损益后,将条目添加到 map

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

在程序结束时,迭代并显示 map 中每只股票的损益。

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

关于java - 每只股票如何输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43566726/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com