Question:
How can you calculate compound interest in java?
Answer:
Formula: amount = principal (1+rate)^years
Java: amount = principal * Math.pow(1+rate, years)
Java: amount = principal * Math.pow(1+rate, years)
Code:
import java.util.Scanner; public class Interest { public static void main(String[] args) { Scanner in = new Scanner( System.in ); double principal; double rate; double interest; System.out.print("Enter the initial investment: "); principal = in.nextDouble(); System.out.print("Enter the annual interest rate: "); rate = in.nextDouble(); System.out.print("Please enter the number of years: "); int years = in.nextInt(); principal = principal * Math.pow(1+rate, years); System.out.print("The future value: "); System.out.printf("%.2f\n", principal); } }
Output:
$ java Interest Enter the initial investment: 100.00 Enter the annual interest rate: .05 Please enter the number of years: 10 The future value: 162.89