object CompoundInterestCalculator {
def calculateCompoundInterest(principal: Double, rate: Double, years: Double): Double = {
// Validate input: all values must be non-negative
if (principal < 0 || rate < 0 || years < 0) {
println("Error: Principal, rate, and years must be non-negative values.")
return -1
}
// Calculate total amount using the compound interest formula
val amount = principal * Math.pow(1 + rate / 100, years)
// Return compound interest (total amount - principal)
amount - principal
}
def main(args: Array[String]): Unit = {
val principal = 100000.0
val rate = 3.5
val years = 5.0
val compoundInterest = calculateCompoundInterest(principal, rate, years)
if (compoundInterest >= 0) {
println(f"Principal Amount: $$${principal}%.2f")
println(f"Annual Interest Rate: ${rate}%.2f%%")
println(f"Years: ${years}%.2f")
println(f"Compound Interest: $$${compoundInterest}%.2f")
println(f"Total Amount: $$${principal + compoundInterest}%.2f")
}
}
}
/*
run:
Principal Amount: $100000.00
Annual Interest Rate: 3.50%
Years: 5.00
Compound Interest: $18768.63
Total Amount: $118768.63
*/