Search code examples
javapow

Error when trying to use math powers in Java


I am trying to do the equation FinalValue = InitialDeposit * (1 + r)^t where t = years and r = rate, but I'am having the hardest time figuring out the proper format.

This is what I have, but it keeps throwing a conversion error in the printf method.

Here is my code:

package cs520.hw2.part1;

import java.lang.Math;

public class BankingProceduralStyle {

    public static void main(String[] args) {

        // bankACalc;
        int bankAyears = 3;
        double bankADeposit = 5000;
        double bankARate = 0.04;

        double bankAFinalValue = bankADeposit * (1 + bankARate) * Math.pow(0.04, 3);

        System.out.printf("BankA %s CD of %.2f at 4.00% rate is worth $%.2f ", bankAyears, bankADeposit, bankAFinalValue);

     }
}

Solution

  • First, your calculation is wrong.

    double bankAFinalValue = bankADeposit * Math.pow((1 + bankARate), bankAyears);
    

    Then fix your printf statement: 4.00% should be 4.00%%.