public class CompoundInterestCalculator {
public static double calculateCompoundInterest(double principal, double rate, double years) {
if (principal < 0 || rate < 0 || years < 0) {
System.out.println("Error: Principal, rate, and years must be non-negative values.");
return -1;
}
// Calculate total amount using the compound interest formula
double amount = principal * Math.pow(1 + rate / 100, years);
// Return compound interest
return amount - principal;
}
public static void main(String[] args) {
double principal = 100000;
double rate = 3.5;
double years = 5;
double interest = calculateCompoundInterest(principal, rate, years);
if (interest >= 0) {
System.out.printf("Principal Amount: %.2f%n", principal);
System.out.printf("Annual Interest Rate: %.2f%%%n", rate);
System.out.printf("Years: %.2f%n", years);
System.out.printf("Compound Interest: %.2f%n", interest);
System.out.printf("Total Amount: %.2f%n", principal + interest);
}
}
}
/*
run:
Principal Amount: 100000.00
Annual Interest Rate: 3.50%
Years: 5.00
Compound Interest: 18768.63
Total Amount: 118768.63
*/