LearnFrenzy
Sign in Take a free test

Java Basics, Syntax and Data Types · Java Basics Programs · Question 1

Simple and compound interest calculator in Java Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

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.

Solution
Main.java
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);
    }
}

Output Verified by compiling and running

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.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links