Read the principal, annual rate and years, and print the simple interest, compound interest (compounded yearly) and the final amounts, formatted to two decimal places.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double principal = in.nextDouble();
double rate = in.nextDouble();
int years = in.nextInt();
double simple = principal * rate * years / 100;
double amount = principal * Math.pow(1 + rate / 100, years);
double compound = amount - principal;
System.out.printf("Simple interest: %,.2f (total %,.2f)%n", simple, principal + simple);
System.out.printf("Compound interest: %,.2f (total %,.2f)%n", compound, amount);
System.out.printf("Difference: %,.2f%n", compound - simple);
}
}
Simple interest: 18,750.00 (total 68,750.00) Compound interest: 21,781.47 (total 71,781.47) Difference: 3,031.47
Math.pow computes (1 + r)ⁿ; %,.2f adds thousands separators and two decimals. Scanner reads numbers separated by any whitespace.