Java Program to Calculate Simple Interest
Program Structure and Explanation
The Java program to calculate simple interest consists of several key components:
- Class Definition: The class
SimpleInterestCalculator
encapsulates the entire program. - Main Method: The
main
method is the entry point of the program where the logic is executed. - Input Handling: Using the
Scanner
class to read inputs for principal amount, rate of interest, and time. - Calculation: A method
calculateSimpleInterest
is defined to compute the simple interest. - Output: The calculated simple interest is printed to the console.
Java Program
import java.util.Scanner;
/**
* A class to calculate Simple Interest based on user inputs for principal, rate, and time.
*/
public class SimpleInterestCalculator {
/**
* Main method - entry point of the program.
*
* @param args Command line arguments
*/
public static void main(String[] args) {
// Create a Scanner object to read input
Scanner scanner = new Scanner(System.in);
// Prompt the user for principal amount
System.out.print("Enter the principal amount: ");
double principal = scanner.nextDouble();
// Prompt the user for rate of interest
System.out.print("Enter the rate of interest: ");
double rate = scanner.nextDouble();
// Prompt the user for time in years
System.out.print("Enter the time in years: ");
double time = scanner.nextDouble();
// Calculate the simple interest
double simpleInterest = calculateSimpleInterest(principal, rate, time);
// Display the simple interest
System.out.println("The Simple Interest is: " + simpleInterest);
// Close the scanner
scanner.close();
}
/**
* Method to calculate simple interest.
*
* @param principal The principal amount
* @param rate The rate of interest
* @param time The time period in years
* @return The calculated simple interest
*/
public static double calculateSimpleInterest(double principal, double rate, double time) {
return (principal * rate * time) / 100;
}
}
Explanation
The program begins by importing the Scanner
class to handle user input. The main
method serves as the entry point of the application. It prompts the user to input the principal amount, rate of interest, and time period in years.
After collecting the inputs, the program calls the calculateSimpleInterest
method, which computes the simple interest using the formula:
Simple Interest = (Principal * Rate * Time) / 100
Finally, the calculated simple interest is displayed to the user, and the Scanner
object is closed to free up resources.