使用for循环来比较多个投资选项

时间:2015-02-13 19:11:57

标签: java finance

for循环中的乘数随着每年的变化而变化,但由于某种原因,在计算年度计算时不会应用它。现在唯一有效的乘数是当用户在提示每年复利的次数时输入值1-12。通常情况是每日,每月,每季度或每年复利。它不适用于每日。

    import java.util.Scanner;

    /**
       This program compares CD /Investment plans input by the year
       broken down by the requirements below:

       This program creates a table of compound interest investment growth over time
       Broken down by: a) year b) balance at end of year
       Finance formula of A= P(1+ r/n)^n*t is used:
       A = Future Value         | P = Initial Investment
       r = annual interest rate |n = times interest is compounded/year
       t = years invested
    */ 

     public class InvestmentTableFirstTest
     {
        public static void main(String[] args)
        {
             Scanner in = new Scanner(System.in);

             String bestBankName = "";
             double bestGrowth = 0;
             boolean done = false;

             while(!done)
             {
                 System.out.print("Plan name (one word, Q to quit): ");
                 String bankName = in.next();
                 if (bankName.equals("Q"))
                 {
                       done = true;
                 }
                 else
                 {
                      System.out.print("Please enter your principal investment: ");
                      final double PRINCIPAL_INVESTMENT = in.nextDouble();
                      System.out.print("Please enter the annual interest rate: ");
                      double iRate = in.nextDouble();
                      System.out.print("Please enter number of times interest is compounded per year:  ");
                      final double INCREMENT = in.nextDouble();      
                      System.out.print("Enter number of years: ");
                      int nyears = in.nextInt();

                      iRate = iRate/100; System.out.println("iRate:" + iRate);

                      //Print the table of balances for each year

                       for (int year = 1; year <= nyears; year++)
                       {
                        double MULTIPLIER = INCREMENT * year;
                        System.out.println("Multiplier: " + MULTIPLIER); // I've included this print statement to show that the multiplier changes with each passing year
                        double interest = 1 + (iRate/INCREMENT);
                        double balance = PRINCIPAL_INVESTMENT;
                        double growth =  balance * Math.pow(interest, MULTIPLIER);
                        growth = growth - PRINCIPAL_INVESTMENT;                      
                        balance = balance + growth;                                  
                        System.out.printf("Year: %2d  Interest Earned:   $%.2f\t   Ending Balance:   $%.2f\n", year, growth, balance);

                       if (bestBankName.equals("") || bestGrowth > growth) // || bestBankName > growth
                       {
                            bestBankName = bankName;  // bestBankName = bankName
                            bestGrowth = growth; // mostGrow = growth
                       }
                          System.out.println("Earning with this option: " + growth);        
                  }
             }

         } 
            System.out.println("Best Growth: " + bestBankName);
            System.out.println("Amount Earned: " + bestGrowth);       
       }
    }

2 个答案:

答案 0 :(得分:0)

这只是一个简单的错误。您正在比较(bestBankName.equals("") || bestGrowth > growth),即如果您当前的增长(因此第一家银行集)的增长率高于第二家银行。换句话说,你翻了箭头。您需要改为if (bestBankName.equals("") || bestGrowth < growth)

答案 1 :(得分:0)

不是一个学习机会的答案(我希望它不违反任何SO法律)。当您轻松进入设计基础时,此变体可能有助于将其视为使用简单值对象的示例。

我提出了大部分逻辑。

价值类定义&amp; main():

<强> InvestmentTableFirstTest.java

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class InvestmentTableFirstTest
{
    public static void main(String[] args)
    {
        Scanner scanIn = new Scanner(System.in);
        String bestBankName = "";
        double bestGrowth = 0.0;
        List<InvestmentOption> investmentOptions = new ArrayList<InvestmentOption>();

        // some information for testing
        InvestmentOption boa = new InvestmentOption("Bank of America", 5000, 1.15, 12, 5);
        InvestmentOption st = new InvestmentOption("Sun Trust", 5000, 2.3, 12, 5);
        InvestmentOption wf = new InvestmentOption("Wells Fargo", 5000, 5.3, 12, 5);

        investmentOptions.add(boa);
        investmentOptions.add(st);
        investmentOptions.add(wf);

        // you could wrap this with conditional logic to obtain multiple
        // investment profiles from the user.
        InvestmentOption userProvided = getInvestmentOptionFromUser(scanIn);
        investmentOptions.add(userProvided);

        // iterate over each bank in the list, evaluate growth
        // and update 'best bank' if the bank being evaluated
        // provides better growth than the current 'best bank'
        for (InvestmentOption currentInvestmentOption : investmentOptions)
        {
            String bankName = currentInvestmentOption.getBankName();
            double PRINCIPAL_INVESTMENT = currentInvestmentOption.getInvestment();
            double iRate = currentInvestmentOption.getInterestRate() /100;
            double INCREMENT = currentInvestmentOption.getCompoundPerYear();
            double nyears = currentInvestmentOption.getYears();
            double MULTIPLIER, interest, balance, growth = 0.0;

            // calculate growth
            for (int year = 1; year <= nyears; year++)
            {
                MULTIPLIER = INCREMENT * year;
                interest = 1 + (iRate/INCREMENT);
                balance = PRINCIPAL_INVESTMENT;
                growth =  balance * Math.pow(interest, MULTIPLIER);
                growth = growth - PRINCIPAL_INVESTMENT;
            }

            currentInvestmentOption.setGrowth(growth);
            System.out.println("Earning with " + bankName + "  " + growth);

            // compare earnings. If the bank being evaluated in this
            // iteration provides a better investment, set it as the
            // best investment option
            if (currentInvestmentOption.getGrowth() > bestGrowth)
            {
                bestGrowth = currentInvestmentOption.getGrowth();
                bestBankName = currentInvestmentOption.getBankName() ;
            }
        }
        System.out.println("\n\nBest Growth: " + bestBankName);
        System.out.println("Amount Earned: " + bestGrowth);
    }

    private static InvestmentOption getInvestmentOptionFromUser(Scanner in)
    {
        InvestmentOption iOption;
        String bankName;
        double principalInvestment, iRate, increment;
        int nyears;

        System.out.print("Plan name : ");
        bankName = in.next();
        System.out.print("Please enter your principal investment: ");
        principalInvestment = in.nextDouble();
        System.out.print("Please enter the annual interest rate: ");
        iRate = in.nextDouble();
        System.out.print("Please enter number of times interest is compounded per year:  ");
        increment = in.nextDouble();
        System.out.print("Enter number of years: ");
        nyears = in.nextInt();

        iOption = new InvestmentOption(bankName, principalInvestment, iRate, increment, nyears);
        return iOption;
    }
}

<强> Investment.java

public class InvestmentOption
{
    private String bankName;
    private double investment;
    private double interestRate;
    private double compoundPerYear;
    private int years;
    private double growth;

    public InvestmentOption(String pBankName, double pInvestment, double pInterestRate, double pCompoundPerYear, int pYears)
    {
        bankName = pBankName;
        investment = pInvestment;
        interestRate = pInterestRate;
        compoundPerYear = pCompoundPerYear;
        years = pYears;
    }

    public double getGrowth()
    {
        return growth;
    }

    public void setGrowth(double pGrowth)
    {
        growth = pGrowth;
    }

    public String getBankName()
    {
        return bankName;
    }


    public double getInvestment()
    {
        return investment;
    }

    public double getInterestRate()
    {
        return interestRate;
    }

    public double getCompoundPerYear()
    {
        return compoundPerYear;
    }

    public int getYears()
    {
        return years;
    }
}