使用 for-loop 比较多个投资选项

Using for-loop to compare multiple investment options

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

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

与其说是一个答案,不如说是一个学习机会(我希望它不会违反任何 SO 法律)。当您逐渐了解设计基础知识时,将此变体作为使用简单值对象的示例可能会有所帮助。

我保留了您介绍的大部分逻辑。

值 class 定义 & 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;
    }
}