CODE TO CREATE A SHARE COMPOUNDING CALCULATOR IN JAVA

import java.util.Scanner;

public class ShareCompoundingCalculator {

    public static void main(String[] args) {
        // Create a Scanner object to capture input
        Scanner scanner = new Scanner(System.in);

        // Input: Initial investment
        System.out.print("Enter the initial investment (in currency): ");
        double principal = scanner.nextDouble();

        // Input: Annual interest rate (percentage)
        System.out.print("Enter the annual interest rate (in %): ");
        double annualInterestRate = scanner.nextDouble();

        // Input: Number of years
        System.out.print("Enter the number of years: ");
        int years = scanner.nextInt();

        // Input: Number of times interest is compounded per year
        System.out.print("Enter the number of times the interest is compounded per year: ");
        int timesCompounded = scanner.nextInt();

        // Calculate the compounded amount using the formula
        double compoundedAmount = calculateCompoundedAmount(principal, annualInterestRate, years, timesCompounded);

        // Output the result
        System.out.printf("After %d years, your investment will grow to: %.2f\n", years, compoundedAmount);
    }

    /**
     * Method to calculate the compounded amount
     * Formula: A = P (1 + r/n)^(nt)
     * Where:
     * A = the future value of the investment/loan, including interest
     * P = the principal investment amount (initial deposit or loan amount)
     * r = annual interest rate (decimal)
     * t = number of years the money is invested or borrowed for
     * n = number of times that interest is compounded per unit t
     */
    public static double calculateCompoundedAmount(double principal, double annualInterestRate, int years, int timesCompounded) {
        // Convert percentage to decimal
        double ratePerPeriod = annualInterestRate / 100;

        // Apply the compound interest formula
        return principal * Math.pow(1 + (ratePerPeriod / timesCompounded), timesCompounded * years);
    }
}
Java

How the Code Works:

Output: Displays the future value after compounding the interest over the specified period.

Inputs:

Initial investment (principal)

Annual interest rate (percentage)

Number of years of the investment

Number of times the interest is compounded per year

Calculation:

Uses the compound interest formula: A=P(1+rn)ntA = P \left(1 + \frac{r}{n}\right)^{nt}A=P(1+nr​)nt Where:

AAA is the amount of money accumulated after n years, including interest.

PPP is the principal amount (initial investment).

rrr is the annual interest rate in decimal.

ttt is the time in years.

nnn is the number of times that interest is compounded per year.

Leave a Reply

Your email address will not be published. Required fields are marked *

Resize text
Scroll to Top