Huntress
Huntress

Reputation: 31

Compound Interest calculator isn't giving me correct data?

I have a compound interest calculator, but when I run the code and input the following numerals when it asks for it:

Principal: 10000 Rate: 0.02 Years:10

and choose "Annual" which is already set up so that if I or a user enters that particular string, the choice variable will automatically become 1 (or the other values already set if I enter the word Quarterly or Monthly). However, I'm supposed to be getting a value of: $12189.94 and am instead getting a value of:10200.0 Where am I doing wrong in my code?

import java.util.Scanner;
import java.lang.Math;
public class CompoundInterest {

public static void main (String [] args)
        { 
            Scanner cool = new Scanner (System.in);
double saving, rate;
int principal, years;
int choice;

System.out.println("Please enter you principal investment:");
/*Print statment prompts user to enter their principal investment*/
principal = cool.nextInt();

 System.out.println("Would you like to have a regular investment plan?");
/* Print out statement asks user if they would like to participate in a regular investment plan*/
String question =cool.next();

System.out.println("Please enter the number of years that you wish to invest for:");
/* Print statement prompts user to enter the number of years that they wish to invest for*/
years = cool.nextInt();

System.out.println("Please enter the return rate per year:");
/* Print statement prompts user to enter the return rate per year*/
rate = cool.nextDouble();

 System.out.println("What type of investment plan would you prefer (Annual, Quarterly, or Monthly)?");
String quest =cool.next();

 if ("Annual".equalsIgnoreCase(quest))
{ choice =1;

 }
 else if ("Quarterly".equalsIgnoreCase(quest)){
     choice = 4;
 }
 else if ("Monthly".equalsIgnoreCase(quest)){
     choice = 12;
 }
 else {
     choice = 0;
     System.out.println("Please choose a investment plan or speak to a financial advisor.");
 }

saving = principal*(1+(rate/choice))*Math.pow(choice,years);
System.out.println(saving);

Upvotes: 0

Views: 167

Answers (2)

Huntress
Huntress

Reputation: 31

Thank you to everyone for providing suggestions. It just seemed that I needed to use:

saving = principal * Math.pow(1+(double) (rate/ (choice)), choice * years);

In order for my equation to work as it seems my equation wasn't properly taking into consideration my integer values as saving is categorized as a double.

Upvotes: 1

tfogo
tfogo

Reputation: 1436

Your formula for calculating interest is incorrect. It should be:

saving = principal*Math.pow(1+(rate/choice), choice*years);

See the correct formula here: https://en.wikipedia.org/wiki/Compound_interest#Periodic_compounding

Upvotes: 0

Related Questions